android (change string in java code)

Jack Trowbridge picture Jack Trowbridge · Jan 2, 2012 · Viewed 13.8k times · Source

In the /res/values folder of my android project i have a string and that is referenced in a text view in my xml file, i want to change the string in my java file.

As you can see below in the code i have made a string variable and then below that i have set what the string variable is set to, which is where the string is located. where i have "here" posed in the code that's where i want to change to string in the values folder. but i don't know what code to use to set it.

I could just change the text in a text view from my java file, which i know how to do, but that is an old way and it sets of a warning so i would rather use a string which is the best way to do so.

With my knowledge of changing text in a text view i have basically guessed my way to this stage but i don't know how to go any further could any one give me some advice on what to do, thanks.

String string;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    counter = 0;
    add = (Button) findViewById(R.id.badd);
    sub = (Button) findViewById(R.id.bsub);
    reset = (Button) findViewById(R.id.breset);
    display = (TextView) findViewById(R.id.tvdisplay);
    string = (String) getString(R.string.counter);

    add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
               ((///////////////here////////////////))
            counter++;

        }
    });

Answer

Squonk picture Squonk · Jan 2, 2012

You cannot modify the text assigned to <string> elements of a /res/values/strings.xml file at runtime. They're constants so effectively final.

You also cannot change a layout xml file at runtime. If you've created a layout with a TextView that has its android:text attribute set to some initial resource string, that is basically an 'initial' value and cannot be changed to something else at runtime.