Jack Trowbridge
Jack Trowbridge

Reputation: 3251

android (change string in java code)

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++;

        }
    });

Upvotes: 7

Views: 15622

Answers (3)

Squonk
Squonk

Reputation: 48871

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.

Upvotes: 3

WarrenFaith
WarrenFaith

Reputation: 57702

You told us a lot of changing text, but you don't said what the text should be. I need to guess, too:

The strings.xml file should be used for texts that might change for different languages. If you just want to change the text of a counter, you shouldn't do it via strings.xml as the numbers are universal :)

Try to go with that:

display.setText(String.valueOf(counter)); 

Upvotes: 2

Will Tate
Will Tate

Reputation: 33509

You will want to use the setText() method.

display.setText("text");

Upvotes: 0

Related Questions