How to set OnClickListener on a RadioButton in Android?
Asked Answered
P

9

131

I have two RadioButtons inside a RadioGroup. I want to set OnClickListener on those RadioButtons. Depending on which RadioButton is clicked, I want to change the text of an EditText. How can I achieve this?

Precess answered 30/11, 2011 at 9:37 Comment(0)
H
259

I'd think a better way is to use RadioGroup and set the listener on this to change and update the View accordingly (saves you having 2 or 3 or 4 etc listeners).

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);        
    radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() 
    {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // checkedId is the RadioButton selected
        }
    });
Handmaid answered 30/11, 2011 at 9:51 Comment(4)
Wasn't working for me, Eclipse suggested I add @Override, and that fixed. ThanksLippi
yea I would use radiogroup except it doesnt work unless its a direct parent in the xml and I cant keep it as a direct parent since this stupid radiobutton cannot be aligned to center so I had to enclose it in a linearlayout ...Bougainville
you could try centering the radiobutton by putting android:gravity="center" in the xml under the RadioGroup tag. @RudolfReinKozloski
What do we do if the radiobutton is dynamically created, and doesnt have an id?Astarte
S
48

Hope this will help you...

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

and

OnClickListener first_radio_listener = new OnClickListener (){
 public void onClick(View v) {
   //Your Implementaions...
 }
};
Stagecraft answered 30/11, 2011 at 9:47 Comment(2)
Worked like a charm, don't forget to add a semicolon after your last curly bracket on your on click listenerEgeria
Oldie but goodie. The accepted answer is leaner but doesn't handle the case of a user selecting something that's already selected. This handles it. Shame the radiogroup listener doesn't handle "setSelected" without regard for "changed".Quianaquibble
I
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();
        }
    });
Ilise answered 28/10, 2014 at 21:7 Comment(1)
group is needed in RadioButton rb=(RadioButton)group.findViewById(checkedId);Baywood
A
23

The question was about Detecting which radio button is clicked, this is how you can get which button is clicked

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;
                }
            }
        });
Argonaut answered 3/5, 2016 at 12:14 Comment(0)
K
15

For Kotlin Here is added the lambda expression and Optimized the Code.

   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
            }
        }
    }

Hope this will help you. Thanks!

Kerb answered 8/2, 2020 at 17:5 Comment(2)
Helped me a lot! Thanks!Yonina
This answer always help.Ormuz
M
10

You could also add listener from XML layout: android:onClick="onRadioButtonClicked" in your <RadioButton/> tag.

<RadioButton android:id="@+id/radio_pirates"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/pirates"
    android:onClick="onRadioButtonClicked"/>

See Android developer SDK- Radio Buttons for details.

Milliary answered 19/10, 2014 at 19:48 Comment(0)
F
9

Since this question isn't specific to Java, I would like to add how you can do it in 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
        }
    }
})

Here radio_group_id is the assigned android:id of the concerned RadioGroup. To use it this way you would need to import kotlinx.android.synthetic.main.your_layout_name.* in your activity's Kotlin file. Also note that in case the radioGroup lambda parameter is unused, it can be replaced with _ (an underscore) since Kotlin 1.1.

Fincher answered 7/8, 2017 at 13:52 Comment(0)
A
7

Just in case someone else was struggeling with the accepted answer:

There are different OnCheckedChangeListener-Interfaces. I added to first one to see if a CheckBox was changed.

import android.widget.CompoundButton.OnCheckedChangeListener;

vs

import android.widget.RadioGroup.OnCheckedChangeListener;

When adding the snippet from Ricky I had errors:

The method setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener) in the type RadioGroup is not applicable for the arguments (new CompoundButton.OnCheckedChangeListener(){})

Can be fixed with answer from Ali :

new RadioGroup.OnCheckedChangeListener()
Acadian answered 7/12, 2014 at 23:26 Comment(0)
L
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()          
        });
Logjam answered 4/9, 2019 at 16:44 Comment(2)
Please provide an explanation for this answer instead of simply posting code.Aili
last line need to be: 'String slectedValue=radioButton.getText().toString()'Wandering

© 2022 - 2024 — McMap. All rights reserved.