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 some开发者_开发问答one please tell me how to do it in my code?
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.");
First we need to find a Button
:
Button mButton = (Button) findViewById(R.id.my_button);
After that, you must implement View.OnClickListener
and there you should find the TextView
and execute the method setText
:
mButton.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
mTextView.setText("Some Text");
}
});
First, add a textView in the XML file
<TextView
android:id="@+id/rate_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/what_U_want_to_display_in_first_time"
/>
then add a button in xml file with id btn_change_textView and write this two line of code in onCreate()
method of activity
Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);
then use clickListener()
on button object like this
btn.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
textView.setText("write here what u want to display after button click in string");
}
});
精彩评论