java - 如何修复 setError 消息以不同的语言出现?
问题描述
我创建了一个登录页面,该页面支持 2 种不同的语言(英语和法语)。
当我从一种语言翻译到另一种语言时,该页面工作正常。
但问题是当我切换到法语时,字段验证的setError 消息不再出现。
此代码将根据语言选择加载页面:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.eng:
String languageToLoad = "en";
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.activity_main);
break;
case R.id.fr:
languageToLoad = "fr";
locale = new Locale(languageToLoad);
Locale.setDefault(locale);
config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.activity_main);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
这是 Username 字段和setError 消息的验证:
private boolean validateUsername(){
String username = usernameEditText.getText().toString().trim();
if(username.isEmpty()){
usernameEditText.setError("Field can't be empty");
return false;
} else if(username.length() > 15){
usernameEditText.setError("Username too long");
return false;
} else {
usernameEditText.setError(null);
return true;
}
}
XML 代码:
<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/usernameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:ems="10"
android:hint="@string/YourUsername"
android:inputType="textPersonName"
android:maxLength="15"
app:errorEnabled="true" />
<Button
android:id="@+id/signupButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/test3"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:onClick="signupLogin"
android:hint="@string/login" />
</android.widget.RelativeLayout>
两种语言之间的弹出消息:
在这里我用英语设置错误消息但是有什么方法可以添加到 setError 消息以支持不同的语言?
谢谢!
解决方案
使用setError
来自字符串资源的消息并使用本地化字符串作为首选语言和英语
推荐阅读
- javascript - Overwrite permissions for discord bot to mute a role in all text/voice channels
- html - 调用属于不同应用的视图名称
- python - for 循环实例化中的 str.split() 会导致执行速度变慢吗?
- python - 如何从apply方法中获取map的第二个参数?
- git - 如何 .gitignore 子目录的内容?
- java - 为使用节点的堆栈创建一个 int search(Object o) 方法
- linux - 尝试在新的 Raspberry Pi 安装上安装 cloudflared 时出现“非法指令”错误
- java - 事件处理程序和 setOnAction?
- javascript - 如何删除小于给定值但不是最后一个值的值?
- database - 使一对多关系适应 DynamoDB (NoSQL)