How to change the value of a string in XML?

Asked

Viewed 1,385 times

4

There is a way to change a string value in XML.

I know how to get the value through getResource().getString(R.string.value); but I don’t know how to change the value directly in XML. Is this allowed? Or the values created in XML are constant (immutable)?

1 answer

4


According to that answer in the SOEN, what you want is not possible - the string.xml in fact it is read-only. The recommended alternative is to use SharedPreferences: a way to create and persist user preferences data.

At this link has an example of how to use them (if this alternative really suits you, of course):

public class Calc extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle state){
       super.onCreate(state);
       . . .

       // Recupera as preferências salvas
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       boolean silent = settings.getBoolean("silentMode", false);
       setSilent(silent);
    }

    @Override
    protected void onStop(){
       super.onStop();

      // Atribui uma nova preferência; isso é feito através de um Editor
      // Todos os objetos são de android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", mSilentMode);

      // Confirma as edições
      editor.commit();
    }
}
  • Thank you. I’m going to study this Sharedpreferences , I think this is really.

  • 2

    @Zeca You can accept this answer as the correct one, making it clear to everyone that it has solved the problem and giving reputation to you and the author of the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.