取消选择单选按钮的替代方法

9
有没有可能通过单击已选中的RadioButton来取消选中它?
1个回答

21
RadioGroup radioGroup;
RadioButton radioButton1;
RadioButton radioButton2;
RadioButton radioButton3;

boolean hack = false;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    radioGroup = (RadioGroup) findViewById(R.id.rg);
    radioButton1 = (RadioButton) findViewById(R.id.r1);
    radioButton2 = (RadioButton) findViewById(R.id.r2);
    radioButton3 = (RadioButton) findViewById(R.id.r3);

    OnClickListener radioClickListener = new OnClickListener()
    {

        public void onClick(View v)
        {
            if (v.getId() == radioGroup.getCheckedRadioButtonId() && hack)
            {
                radioGroup.clearCheck();
            }
            else
            {
                hack = true;
            }
        }
    };

    OnCheckedChangeListener radioCheckChangeListener = new OnCheckedChangeListener()
    {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            hack = false;
        }
    };

    radioButton1.setOnCheckedChangeListener(radioCheckChangeListener);
    radioButton2.setOnCheckedChangeListener(radioCheckChangeListener);
    radioButton3.setOnCheckedChangeListener(radioCheckChangeListener);

    radioButton1.setOnClickListener(radioClickListener);
    radioButton2.setOnClickListener(radioClickListener);
    radioButton3.setOnClickListener(radioClickListener);

}

好的,现在我已经更新了。这应该可以工作Philipz。


好的,我稍后会测试一下,非常感谢你的回答,谢谢! - user2443607
嘿,老兄,它从来不会选中RadioButton,因为它先选中然后又取消选中,所以最终状态是未选中!:/ - user2443607
是的,Philipz测试了它并发现它是你告诉他的那样。然而,我通过布尔值的帮助成功让它工作了...将在几分钟内更新答案。 - Varun
@Philipz 更新了代码。这是一个简单的解决方法,运行良好。 - Varun
@Varun,这个解决方案对我来说不起作用😞 问题:如果我第一次点击未选中的按钮,它会变为选中状态,然后我再次点击它将取消选中。但是,如果我试图再次点击它,它却没有被选中。 - Bipin Vayalu
试一下这个。https://github.com/ragunathjawahar/deselectable-radio-button/blob/master/res/layout/demo.xml - dmSherazi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接