I want to change the of a TextView
by pressing a Button
, but don't understand how to do it properly.
This is part of my layout:
<TextView android:id="@+id/counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change text!" />
And this is my activity:
public class Click extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
// ???
}
});
}
}
What should I put inside onClick()
method?
yourTextView.setText("New text");
Refer
findViewById
andsetText
methods.You can do it with the setText("anything") method.
Edit: Here is your handler:
TextView view = (TextView) findViewById(R.id.counter);
According to: http://developer.android.com/reference/android/widget/TextView.html
Java only no XML version
To make things more explicit:
Tested on Android 22.
In
onclick
, take the object of the TextView and set the desired text like so: