How To Change A Textview's Text By Pressing A Button
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:
Solution 1:
According to: http://developer.android.com/reference/android/widget/TextView.html
TextViewview= (TextView) findViewById(R.id.counter);
view.setText("Do whatever");
Solution 2:
- Find the textview by id
- Change the text by invoking
yourTextView.setText("New text");
Refer findViewById
and setText
methods.
Solution 3:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
publicclassClickextendsActivity {
int i=0;
protectedvoidonCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
finalTextViewmTextView= (TextView) findViewById(R.id.counter)
mTextView.setText("hello "+i);
finalButtonbutton= (Button) findViewById(R.id.button);
button.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(View v) {
// Perform action on click
i=i+1;
mTextView.setText("hello "+i);
}
});
}
}
Hope this serve your need
Solution 4:
TextViewtv= (TextView) v;
tv.setText("My new text");
Edit: Here is your handler:
button.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(View v) {
//TextView tv = (TextView) v; //code correctedTextView tv= (TextView) findViewById(R.id.counter);
tv.setText("My new text");
}
});
TextView view = (TextView) findViewById(R.id.counter);
Solution 5:
You can do it with the setText("anything") method.
Post a Comment for "How To Change A Textview's Text By Pressing A Button"