取消选中单选按钮

A B*_*A B 4 android if-statement radio-button checked uncheck

该应用程序是一个步进音序器应用程序,具有16个无线电组,每组有8个按钮.除非我使用我创建的清除按钮清除所有放射线组,否则除非一个组选择了一个按钮,否则它可以完美地工作.我想要添加的是一些代码,表示当再次选择所选单选按钮时,它会像切换一样关闭.我尝试使用切换,但随后出现了其他问题.下面是对它的一次尝试但是我猜测它是不合适的

final RadioGroup radioGroup1 = (RadioGroup)findViewById(R.id.RadioGroup1);
RadioButton lC1 = (RadioButton)findViewById(R.id.RadioButtonlowC1);

Button D1 = (Button)findViewById(R.id.RadioButtonD1);
        D1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                PdBase.sendFloat("D1", 74);
                int selectedTypeId = radioGroup1.getCheckedRadioButtonId();
                RadioButton D1 = (RadioButton) findViewById(selectedTypeId);
                if(radioGroup1 != null) // This will be null if none of the radio buttons are selected
                       radioGroup1.clearCheck(); 
                PdBase.sendFloat("D1", 0);
            }
        });
Run Code Online (Sandbox Code Playgroud)

spa*_*y21 22

请看我对你的另一个基本相同的问题的答案,我在下面复制了...... :)

我最近有同样的需求 - 有一个无线电组,通过再次点击它可以取消选择所选项目.我发现我无法做到,使用监听器,但我能够做到这一点使用自定义的RadioButton,是这样的...

public class ToggleableRadioButton extends RadioButton {
    // Implement necessary constructors

    @Override
    public void toggle() {
        if(isChecked()) {
            if(getParent() instanceof RadioGroup) {
                ((RadioGroup)getParent()).clearCheck();
            }
        } else {
            setChecked(true);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,该按钮以不同的方式切换,具体取决于其当前状态 - 即,呼叫setChecked(true)按钮与呼叫clearCheck()组.如果setChecked()在两种情况下都使用,则无法立即重新选择刚刚取消选择的按钮 - 逻辑RadioGroup可以阻止它.

要使用此按钮,只需在布局XML中替换您的<RadioButton>标签即可<your.package.ToggleableRadioButton>.