问题
I'm currently trying to make a basic app that incorporates 4 toggle buttons and a textview. The idea is simple: When a button is pressed, the textview will show which buttons are currently being pressed. This can include multiple buttons (such as if, for example 1, 3, and 4 were pressed). Here's the code I've written for it:
TextView buttons;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttons = (TextView)findViewById(R.id.textView1);
}
public void buttonPressed(View v){
boolean check = ((ToggleButton)v).isChecked();
int b1 = 1, b2 = 2, b3 = 3, b4 = 4;
switch(v.getId()){
case R.id.toggleButton1:
if(check){
buttons.setText("Buttons pressed: " + b1);
}
else{
buttons.setText("Buttons pressed:");
}
break;
case R.id.toggleButton2:
if(check){
buttons.setText("Buttons pressed: " + b2);
}
else{
buttons.setText("Buttons pressed:");
}
break;
case R.id.toggleButton3:
if(check){
buttons.setText("Buttons pressed: " + b3);
}
else{
buttons.setText("Buttons pressed:");
}
break;
case R.id.toggleButton4:
if(check){
buttons.setText("Buttons pressed: " + b4);
}
else{
buttons.setText("Buttons pressed:");
}
break;
default:
break;
}
}
Unfortunately, every time I run this program, the textview is overwritten, and I can't get it to validate that multiple buttons are pressed. All suggestions are welcome.
回答1:
If you want your textview always show number of ON buttons, I think you can do this way :
Keep tracks of your buttons
private ToggleButton[] btns = new ToggleButton[4];
In onCreate():
btn[0] = (ToggleButton)findViewById(R.id.toggleButton1);
btn[1] = (ToggleButton)findViewById(R.id.toggleButton2);
btn[2] = (ToggleButton)findViewById(R.id.toggleButton3);
btn[3] = (ToggleButton)findViewById(R.id.toggleButton4);
Then in your buttonPressed handler :
String text = "Buttons pressed: ";
for (int i = 0; i < 4; i++) {
if (btn[i].isCheck()) {
text += (i + 1) + ", ";
}
}
buttons.setText(text);
回答2:
You need to use append() if you don't want to overwrite the text that is already there. So something like
public void buttonPressed(View v){
boolean check = ((ToggleButton)v).isChecked();
int b1 = 1, b2 = 2, b3 = 3, b4 = 4;
switch(v.getId()){
case R.id.toggleButton1:
if(check){
buttons.append("" + b1);
}
else{
buttons.setText("Buttons pressed:");
}
break;
And you can just use buttons.setText("Buttons pressed");
once in onCreate()
then append everything to that.
来源:https://stackoverflow.com/questions/20435380/adding-multiple-values-to-a-textview-android