我的视图中有很多按钮。每个按钮可以有三个背景图像之一。我有一种情况,在一个按钮上单击其他人将状态更改为第一个背景图像。当然,我可以做出难看的切换,记住最后选择的按钮,但是对于这种情况可能有更好的解决方案吗?
由于
public class MyActivity extends Activity {
private Button bt1;
private Button bt3;
private Button bt4;
private Button bt5;
private Button bt6;
private Button bt7;
private Button bt8;
private Button bt9;
@Override
public void onCreate(Bundle savedInstanceState) {
...
bt1 = (Button) findViewById(R.id.bt1);
bt2 = (Button) findViewById(R.id.bt2);
bt3 = (Button) findViewById(R.id.bt3);
...
bt2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
bt2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.select_button2));
bt1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.no_select_button1));
bt3.setBackgroundDrawable(getResources().getDrawable(
R.drawable.no_select_button3));
...
bt9.setBackgroundDrawable(getResources().getDrawable(
R.drawable.no_select_button9));
}
});
bt1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
bt1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.select_button1));
bt2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.no_select_button2));
bt3.setBackgroundDrawable(getResources().getDrawable(
R.drawable.no_select_button3));
...
bt9.setBackgroundDrawable(getResources().getDrawable(
R.drawable.no_select_button9));
}
});
还有其他办法吗?
答案 0 :(得分:0)
我知道它的回答很晚但有人可能需要它。基于this githubt要点,将以下代码添加到OnClick方法:
@Override
public void onClick(View v) {
Button button = (Button) v;
// clear state
mButton1.setSelected(false);
mButton1.setPressed(false);
mButton2.setSelected(false);
mButton2.setPressed(false);
mButton3.setSelected(false);
mButton3.setPressed(false);
// change state
button.setSelected(true);
button.setPressed(false);
}