Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Change strings resource Programmatically

Tags:

Is there a way to do this? For instance, I have a setting in my preferences that can convert between metric and standard units of measurement and when the user changes this I would like to update a few strings to change some labels around within my app.

like image 467
ryandlf Avatar asked Aug 04 '11 05:08

ryandlf


People also ask

Which is the proper way to retrieve a string resource programmatically?

android:text="@string/hello" /> hello); You can use either getString(int) or getText(int) to retrieve a string.

How to add special characters in string XML in Android?

How can I write character & in the strings. xml? In android studio, you can simply press Alt+Enter and it will convert for you.

Why should you use string resources instead of hard coded strings in your apps?

It allows you to easily locate text in your app and later have it translated. Strings can be internationalized easily, allowing your application to support multiple languages with a single application package file (APK).


2 Answers

You can update the label on TextView or anything similar.

  • Get the updated string using update_str = Context.getResources().getString (R.string.update_identifier)
  • Update the label using ((TextView)findViewById (R.id.textview)).setText (updated_str)
like image 117
Vino Avatar answered Oct 24 '22 20:10

Vino


You may use following instructions to fetch saved labels from strings.xml file and show them accordingly at some 'if statement' which could check your

pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) .getString("conversion_mode", "");

String string = getString(R.string.update_identifier);

or

getResources().getString (R.string.update_identifier)

would do the best

getString(int) or getText(int) may be used to retrieve a string. Please note getText(int) will retain any rich text styling applied to the string.

Find the Reference

like image 31
Darpan Avatar answered Oct 24 '22 20:10

Darpan