Updating a TextView after Button is clicked?
I'm trying to make a basic counter.
The idea is that the user presses the button and the app displays how many times the button has been pressed.
My problem is that I am unsure of how to update the text view. My understanding is that the XML parts of it retrieves the strings, which are set in stone upon runtime. So how am I supposed to "update" something that is "final"?
My understanding is that When the button is pressed, I increment num by 1. Then, it gets the prompt string (Clicks: %d) and displays it to the sc开发者_Go百科reen. However, whenever I run this, it just crashes.
public class HelloAndroid extends Activity{
/** Called when the activity is first created. */
int num = 0;
TextView tView;
Button clickhere;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tView = (TextView) findViewById(R.id.textView1);
clickhere = (Button) findViewById(R.id.button1);
clickhere.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
num++;
String display = String.format(getString(R.string.prompt), num);
tView.setText(display);
setContentView(tView);
}
});
}
}
Any help would be appreciated.
You are setting the TextView when it is clicked (not when the button is clicked), I am guessing that is not what you meant to do. I have update your code below to set the TextView when the button is clicked.
public class HelloAndroid extends Activity{
/** Called when the activity is first created. */
int num = 0;
TextView tView;
Button clickhere;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tView = (TextView) findViewById(R.id.textView1);
clickhere = (Button) findViewById(R.id.button1);
clickhere.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String display = String.format(getString(R.string.prompt, Integer.toString(++num)));
tView.setText(display);
}
});
//you don't need an event handler on the TextView (given the description of the problem)
}
}
clickhere.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
num++;
tView.setText(Integer.toString(num));
}
});
this will set your textview equal to num
精彩评论