Android:RadioGroup - 如何配置事件监听器

标签 android listener radio-group android-radiogroup android-radiobutton

据我了解,要判断一个复选框是否被“点击”并判断它是否被选中,可以使用如下代码:

cb=(CheckBox)findViewById(R.id.chkBox1);
        cb.setOnCheckedChangeListener(this);

public void onCheckedChanged(CompoundButton buttonView, 
    boolean isChecked) { 
        if (isChecked) { 
            cb.setText("This checkbox is: checked"); 
        } 
        else { 
            cb.setText("This checkbox is: unchecked"); 
        } 
    }

但是,我无法弄清楚如何为 radio 组执行上述操作的逻辑。

这是我的 RadioGroup 的 xml:

<RadioGroup android:id="@+id/radioGroup1" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
    <RadioButton android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/radio1" android:checked="true" 
    android:text="RadioButton1">
    </RadioButton>
    <RadioButton android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/radio2" android:text="RadioButton2" android:checked="true">
    </RadioButton>
    <RadioButton android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/radio3" android:text="RadioButton3">
    </RadioButton>
</RadioGroup>

问题:我是否需要设置另一个监听器,或者已经存在的监听器也会“注册”这个组?

另外,监听器应该设置在 RadioGroup 还是 RadioButton 上?

最佳答案

这是您获得选中单选按钮的方式:

// This will get the radiogroup
RadioGroup rGroup = (RadioGroup)findViewById(r.id.radioGroup1);
// This will get the radiobutton in the radiogroup that is checked
RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(rGroup.getCheckedRadioButtonId());

要使用监听器,请执行以下操作:

// This overrides the radiogroup onCheckListener
rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
    public void onCheckedChanged(RadioGroup group, int checkedId)
    {
        // This will get the radiobutton that has changed in its check state
        RadioButton checkedRadioButton = (RadioButton)group.findViewById(checkedId);
        // This puts the value (true/false) into the variable
        boolean isChecked = checkedRadioButton.isChecked();
        // If the radiobutton that has changed in check state is now checked...
        if (isChecked)
        {
            // Changes the textview's text to "Checked: example radiobutton text"
            tv.setText("Checked:" + checkedRadioButton.getText());
        }
    }
});

关于Android:RadioGroup - 如何配置事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6780981/

相关文章:

Android:RadioGroup.OnCheckedChangeListener 在我的应用程序中不起作用

java - Android布局文件不允许&、<、>等字符

Android Twilio 错误 "31003"

android - Android 应用上的自定义事件监听器

java - Android Radio Group 多选问题

java - 获取Android中RadioGroup的索引

android - 在午夜更新 Android Widget

android - 使用 JUnit + 的单元测试用例(Android 中的 Robolectric 或 Mockito 或两者)

java - Spring的@JmsListener只从Solace队列接收一条消息

android - 在 Android 上监听通知