问题
i have a toggle button which when set to the on position sets the hint to one of my textview to
"kg"
. the initial hint of the text view is
"st"
which should be shown if the toggle is in the off position.
when i first start the app the textview dispalys
"st"
(which at first is ok as the toggle is in the off position) now when i press the toggle it turns to the on position and displays
"kg"
in the textView (this is also ok.)
now comes the problem. if i click on the toggle again (off position) the textView stays as
"kg"
does anyone know how i could set it to always display "st in the off state and "kg" in the on state.
many thanks in advance
addListenerOnButton();
}
public void addListenerOnButton() {
unitToggle = (Button) findViewById(R.id.unitToggle);
final TextView tw1 = (TextView)findViewById(R.id.tw1);
unitToggle.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer result = new StringBuffer();
tw1.setHint("kg");
回答1:
unitToggle.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer result = new StringBuffer();
if(tw1.getHint().toString().equals("kg"))
tw1.setHint("st");
else
tw1.setHint("kg");
回答2:
The main reason for the said problem is the logic which has not yet been implemented.
When you click the button for the first time it sets the text to "kg" which it will set always on any number of click. since you have written the statement
tw1.setHint("kg");
inside your onClick() method without keeping the state of the button. emphasized text.
In order to make it correct use a boolean flag and change its state on each click and set the text based on the flag value.
The best way to do it is to use ToggleButton which has the inbuilt on/off states so you don't need to have your on boolean flag and set the hint based on the button state.
回答3:
Try
private boolean on=false;
unitToggle.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer result = new StringBuffer();
if(on){
tw1.setHint("kg");
on = true;
}else{
tw1.setHint("st");
on = false;
}
来源:https://stackoverflow.com/questions/10121394/android-toggle-button-state-set-texview-text