选择并取消选择按钮onClick in android

时间:2015-05-24 19:26:47

标签: android button onclick

当按下按钮时,其背景状态发生变化,我希望当我再次按下按钮时,其背景状态将恢复到初始状态。这意味着首先单击选择,然后单击第二次取消选择它。我怎么能这样做?

orderBtn = new OrderButton(getApplicationContext());
orderBtn.setId(i);
orderBtn.setText(option);
orderBtn.setTextColor(Color
                .parseColor("#FFFFFF"));
orderBtn.setBackgroundResource((R.drawable.selector));
orderBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
    v.setSelected(true);
    enabledButton = orderBtn.getId();
    deselectButtons();

}
});

public void deselectButtons() {
    for (int i = 0; i < jsonArray.length(); i++) {
        if (enabledButton != i)
            findViewById(i).setSelected(false);
}

2 个答案:

答案 0 :(得分:0)

使用ToggleButton,您可以使用自定义选择器自定义背景。

<强>更新

根据您的实施,您基本上希望实现Invalidate()功能,如果一个是PanelContainerDesigner,则其他功能基本上是RadioGroup/RadioButton。我强烈建议您不要采用自己的方法,而是使用自定义Turned On,以便您可以使用Turned Off的此功能。

答案 1 :(得分:0)

So, one thing you can do is this:

yourButton.setOnClickListener(new ClickListener(){
int check = 1; //When check = 1 ,you have your FIRST background set to the button

 @Override
 public void Click(View v){
    if(check == 1){
       yourButton.setBackground(R.drawable.secondBackground);
       check = 0;
    }else{
       yourButton.setBackground(R.drawable.firstBackground);
       check = 1;
    }
 }

});

Amyways, I remember I did this by modifying the selector that a toggleButton uses ,but I really,really don't have time to search my old projects and stuff...and as far as optimization goes, the selector should be a bit better ,but if you don't have tons of these buttons to check their backgrounds and keep changing them,you should be fine,I guess.

Let me know if this helped^^