Search code examples
javaandroidtextview

How do I change TextView Value inside Java Code?


I am working on a android program. A user clicks on a button I do some math and I would like to change the values that I have on my view in some TextView objects. Can someone please tell me how to do it in my code?


Solution

  • I presume that this question is a continuation of this one.

    What are you trying to do? Do you really want to dynamically change the text in your TextView objects when the user clicks a button? You can certainly do that, if you have a reason, but, if the text is static, it is usually set in the main.xml file, like this:

    <TextView  
    android:id="@+id/rate"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/rate"
    />
    

    The string "@string/rate" refers to an entry in your strings.xml file that looks like this:

    <string name="rate">Rate</string>
    

    If you really want to change this text later, you can do so by using Nikolay's example - you'd get a reference to the TextView by utilizing the id defined for it within main.xml, like this:

    
    final TextView textViewToChange = (TextView) findViewById(R.id.rate);
    textViewToChange.setText(
        "The new text that I'd like to display now that the user has pushed a button.");