问题
If i press one button and then press the other, the amount adds up on both TextViews. I want them to be separate numbers. I tried google to find a solution but i couldn't find anything. Please help?
public class MainActivity extends Activity {
int clicked = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
{
final TextView text = (TextView) findViewById(R.id.textView2);
final ImageButton button = (ImageButton)findViewById(R.id.imageButton2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
clicked++;
text.setText(" " + clicked + " ");
}
});
}
final TextView text = (TextView) findViewById(R.id.textView1);
text.setText("");
final ImageButton button = (ImageButton)findViewById(R.id.imageButton1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
clicked++;
text.setText(" " + clicked + " ");
}
});
}
}
回答1:
Use two different variables. Clicked is being added to when you press either button. Also choose different names for your buttons, don't name them both button.
ex:
public class MainActivity extends Activity {
int clicked1 = 0;
int clicked2 = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
{
final TextView text = (TextView) findViewById(R.id.textView2);
final ImageButton button2 = (ImageButton)findViewById(R.id.imageButton2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
clicked2++;
text.setText(" " + clicked2 + " ");
}
});
}
final TextView text = (TextView) findViewById(R.id.textView1);
text.setText("");
final ImageButton button1 = (ImageButton)findViewById(R.id.imageButton1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
clicked1++;
text.setText(" " + clicked1 + " ");
}
});
}
}
来源:https://stackoverflow.com/questions/26765576/i-want-to-create-two-button-clickers-that-add-up-different-numbers