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 screen. 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.
If you have a new text to set to the TextView , just call textView. setText(newText) , where newText is the updated text. Call this method whenever newText has changed.
TextView tv1 = (TextView)findViewById(R. id. textView1); tv1. setText("Hello"); setContentView(tv1);
To use preset sizes to set up the autosizing of TextView in XML, use the android namespace and set the following attributes: Set the autoSizeText attribute to either none or uniform. none is a default value and uniform lets TextView scale uniformly on horizontal and vertical axes.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With