简体   繁体   中英

Change value of R.string programmatically?

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();
                }
            }
        }
    }
}

Use built-in mechanism of localization , introduced in android. You don't need to change anything. You just need to specify the new strings.xml for each locale.

如果您想更改应用程序的当前语言,可以使用标准的内置本地化功能并以编程方式更改区域设置

你应该为你的资源添加一个语言环境值并复制它们:每种语言一个,从而让设备根据它的设置选择正确的:检查它http://developer.android.com/resources/tutorials/localization /index.html

I believe using Android's built-in localization features is preferable to implementing it by hand. Here's a guide you can refer to:

http://developer.android.com/guide/topics/resources/localization.html

Unless, of course, we misunderstood your use case, but it does really sound like you are trying to do standard localization :-)

Bruno Oliveira, Developer Programs Engineer, Google

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM