本文介绍了以编程方式更改 R.string 的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种动态更改字符串资源值的方法.我尝试使用反射,但它声称字段值无效".
I'm looking for a way to change the value of a string resource dynamically. I have tried to use reflection but it claims 'invalid value for field'.
我在布局中使用字符串作为值,但需要将它们替换为不同的语言.
I use the strings for values within the layout, but need to swap them out for different languages.
请参阅下面的附加代码.
Please see the attached code below.
public class Lang{
public static void langInit(){
java.lang.reflect.Field[] langStringFields = R.string.class.getFields();
Log.d(Global.TAG,"--> Lang Listing: " + langStringFields.length);
Log.d(Global.TAG,"--> Pref for language:");
String prefInLang = Prefs.cPrefsGet.getString("in_lang","en");
String fieldName = null;
String fieldValue = null;
String newFieldName = null;
String tmpA = "one";
for (int i=0; i<langStringFields.length; i++){
java.lang.reflect.Field field = langStringFields[i];
fieldName = field.getName();
try {
fieldValue = Global.gActivity.getString(field.getInt(R.string.class));
} catch (Exception e) {
e.printStackTrace();
}
if (fieldName.substring(0,2).equals("lo")){
try {
newFieldName = R.string.class.getField(prefInLang + "_" + fieldName.substring(3)).getName();
} catch (Exception e) {
e.printStackTrace();
}
Log.d(Global.TAG,"--> Field: " + fieldName + "value: " + fieldValue + "new field:" + newFieldName);
try {
java.lang.reflect.Field field2 = Class.forName(R.string.class.getName()).getDeclaredField(newFieldName);
field2.setAccessible(true);
field2.set(R.string.class,tmpA.toString());
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
推荐答案
如果您想更改应用程序的当前语言,您可以使用标准的内置本地化功能和 以编程方式更改区域设置.
If you want to change current language for you app you can do it by using standard built-in localization features and changing locale programatically.
这篇关于以编程方式更改 R.string 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!