Change R.string value programmatically?

I am looking for a way to change the value of a string resource dynamically. I tried to use reflection, but it claims "invalid value for field".

I use strings for the values ​​in the layout, but they need to be changed for different languages.

See 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(); } } } } } 
+3
android string resources
Mar 29 2018-11-21T00:
source share
4 answers

If you want to change the current language for your application, you can do this using standard built-in localization functions and changing the language standard programmatically .

+2
Mar 29 2018-11-11T00:
source share

Use the built-in localization mechanism introduced in android. You do not need to change anything. You just need to specify a new strings.xml for each locale.

+3
Mar 29 '11 at 15:04
source share

you should add the locale value to your resources and duplicate them: one for each language, which allows the device to choose the correct option according to its settings: check it there http://developer.android.com/resources/tutorials/localization/index .html

+1
Mar 29 '11 at 15:04
source share

I believe that using the built-in Android localization functions is preferable for its implementation. Here you can refer to the manual:

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

Unless, of course, we understand your use case, but it really sounds like you are trying to perform standard localization :-)

Bruno Oliveira, Software Engineer, Google

+1
Mar 29 '11 at 15:13
source share



All Articles