如何在Android中为RadioButton设置OnClickListener?

131

我在 RadioGroup 中有两个 RadioButton,想要对这些 RadioButton 设置 OnClickListener。根据点击哪个 RadioButton,我想要改变一个 EditText 的文本内容。我该如何实现?

9个回答

259

我认为更好的方法是使用RadioGroup,并在其上设置监听器以相应地更改和更新View(这可以避免您需要2、3、4个监听器的情况)。

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);        
    radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() 
    {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // checkedId is the RadioButton selected
        }
    });

2
对我来说没有起作用,Eclipse建议我添加@ Override,然后问题就解决了。谢谢。 - Jack Franzen
是的,我会使用RadioGroup,但它只能在XML中作为直接父级才能正常工作。由于这个愚蠢的RadioButton无法居中对齐,我不能将其保持为直接父级,所以我不得不将其包含在一个LinearLayout中... - Jaxx0rr
您可以在RadioGroup标签下的xml中添加**android:gravity="center"**尝试居中显示单选按钮。@RudolfRein - OuuGiii
如果单选按钮是动态创建的,并且没有ID,我们该怎么办? - Arjun Issar

48

希望这能帮助到你...

RadioButton rb = (RadioButton) findViewById(R.id.yourFirstRadioButton);
rb.setOnClickListener(first_radio_listener);

并且

OnClickListener first_radio_listener = new OnClickListener (){
 public void onClick(View v) {
   //Your Implementaions...
 }
};

1
运行得很好,不要忘记在您的单击监听器中的最后一个花括号后添加分号。 - inVINCEable
1
老牌但经典。被接受的答案更简洁,但无法处理用户选择已选中的情况。这个可以处理。遗憾的是radiogroup监听器不能忽略“changed”而只使用“setSelected”。 - JamieB

30
 radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // checkedId is the RadioButton selected
            RadioButton rb=(RadioButton)findViewById(checkedId);
            textViewChoice.setText("You Selected " + rb.getText());
            //Toast.makeText(getApplicationContext(), rb.getText(), Toast.LENGTH_SHORT).show();
        }
    });

2
group is needed in RadioButton rb=(RadioButton)group.findViewById(checkedId); - Second Person Shooter

23

这个问题是关于如何检测选中了哪个单选按钮,下面是获取所选按钮的方法:

final RadioGroup radio = (RadioGroup) dialog.findViewById(R.id.radioGroup1);
        radio.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                View radioButton = radio.findViewById(checkedId);
                int index = radio.indexOfChild(radioButton);

                // Add logic here

                switch (index) {
                case 0: // first button

                    Toast.makeText(getApplicationContext(), "Selected button number " + index, 500).show();
                    break;
                case 1: // secondbutton

                    Toast.makeText(getApplicationContext(), "Selected button number " + index, 500).show();
                    break;
                }
            }
        });

15

Kotlin版本中增加了lambda表达式并优化了代码。

   radioGroup.setOnCheckedChangeListener { radioGroup, optionId ->
        run {
            when (optionId) {
                R.id.radioButton1 -> {
                    // do something when radio button 1 is selected
                }
                R.id.radioButton2 -> {
                    // do something when radio button 2 is selected
                }
                // add more cases here to handle other buttons in the your RadioGroup
            }
        }
    }

希望这能对你有所帮助。谢谢!


1
帮了我很多!谢谢! - Artur
这个答案总是有帮助的。 - Abdul Waheed

10
你还可以通过在 <RadioButton/> 标签中添加 android:onClick="onRadioButtonClicked" 来从 XML 布局中添加监听器。
<RadioButton android:id="@+id/radio_pirates"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/pirates"
    android:onClick="onRadioButtonClicked"/>

请查看Android开发者SDK-单选按钮以获取详细信息。


9

由于这个问题并不特定于Java,我想添加一下如何在Kotlin中实现:

radio_group_id.setOnCheckedChangeListener({ radioGroup, optionId -> {
        when (optionId) {
            R.id.radio_button_1 -> {
                // do something when radio button 1 is selected
            }
            // add more cases here to handle other buttons in the RadioGroup
        }
    }
})

这里的radio_group_id是相关RadioGroup分配的android:id。要以这种方式使用它,您需要在活动的Kotlin文件中导入kotlinx.android.synthetic.main.your_layout_name.*。还请注意,如果未使用radioGroup lambda参数,自Kotlin 1.1起可以将其替换为_(下划线)。


7

如果有人对已接受的答案感到困惑,以下内容可能会有所帮助:

OnCheckedChangeListener 接口有多个版本。我添加了第一个版本来检查 CheckBox 是否被更改。

import android.widget.CompoundButton.OnCheckedChangeListener;

vs

import android.widget.RadioGroup.OnCheckedChangeListener;

当我添加来自Ricky的片段时,出现了错误:

类型RadioGroup中的方法setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener)不适用于参数(new CompoundButton.OnCheckedChangeListener(){})

可以使用Ali的答案来解决:

new RadioGroup.OnCheckedChangeListener()

0
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);     
    radioGroup.setOnClickListener(v -> {
                        // get selected radio button from radioGroup
                        int selectedId = radioGroup.getCheckedRadioButtonId();
                        // find the radiobutton by returned id
                        radioButton =  findViewById(selectedId);
                        String slectedValue=radioButton.getText()          
        });

1
请提供此答案的解释,而不仅仅是发布代码。 - ScoobyDrew18
最后一行需要是:“String slectedValue = radioButton.getText().toString()” - Web.11

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