Android: RadioGroup - How to configure the event listener
Asked Answered
K

6

64

From my understanding, to determine if a checkbox is "clicked" and find if it's checked or not, code such as the following can be used:

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"); 
        } 
    }

However, I am unable to work out the logic on how to do the above for a radiogroup.

Here is the xml for my RadioGroup:

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

Question: Do i need to setup another listener, or will the listener already there also "register" this group?

Also, should the listener be set up on the RadioGroup or the RadioButton?

Knowle answered 21/7, 2011 at 18:38 Comment(0)
M
141

This is how you get the checked 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());

To use the listener, you do this:

// 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());
        }
    }
});
Matisse answered 21/7, 2011 at 18:45 Comment(6)
it says: "The local variable rgroup may not have been initialized"Knowle
I just wrote that first line to tell you what rGroup was. To get rGroup, you need to write this: RadioGroup rGroup = (RadioGroup)findViewById(R.id.radioGroup1);Matisse
I dont get it, it tells me the radiogroup is checked... but does not tell me which radio button is checked. Am I missing something?Knowle
Take a look at my answer again. I edited it and put comments for each line so that you know what I am doing. Also, the checked id is not the name of the radiobutton, it's the radiobutton's unique identifier.Matisse
That worked perfectly and also taught me how its all "wired" up in the back, thank you so much!Knowle
I never quite got how this worked before, but your sample code and comments made the lightbulb turn on at lastWorl
U
22

It should be something like this.

RadioGroup rb = (RadioGroup) findViewById(R.id.radioGroup1);
rb.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {

            }
        }

    });

Based on the checkedId, you would know which of the radiobutton has been clicked and then use your above code to figure out if its checked or unchecked. This is homework. ;)

Upsurge answered 21/7, 2011 at 18:48 Comment(3)
Your code works, but i took out the switch and added this instead: tv.setText("blah:"+checkedId); but it gives me some weird numbers for checkedID :(Knowle
CheckedId is the id of the radiobutton that got clicked in the group. You need to use findViewbyId to make sense out of it.Upsurge
I would expect this to work but it doesn't. When I change the selected radiobutton on a 3 button control, I get 3 notifications that checked changed. There seems to be one per button. But for the first notification, button for checkedId has a value of false for Checked. Abiri's solution works for me.Protist
L
19

Using Switch is better:

radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
      public void onCheckedChanged(RadioGroup arg0, int id) {
        switch (id) {
        case -1:
          Log.v(TAG, "Choices cleared!");
          break;
        case R.id.chRBtn:
          Log.v(TAG, "Chose Chicken");
          break;
        case R.id.fishRBtn:
          Log.v(TAG, "Chose Fish");
          break;
        case R.id.stkRBtn:
          Log.v(TAG, "Chose Steak");
          break;
        default:
          Log.v(TAG, "Huh?");
          break;
        }
      }
    });
Lustihood answered 11/8, 2017 at 19:29 Comment(1)
Throws the following warning: Resource IDs will be non-final in Android Gradle Plugin version 5.0, avoid using them in switch case statements.Abeyta
A
7
//Within the Activity that hosts this layout, the following method handles the click event for both radio buttons:

public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();

// Check which radio button was clicked
switch(view.getId()) {
    case R.id.radio_pirates:
        if (checked)
            // Pirates are the best
        break;
    case R.id.radio_ninjas:                       
        if (checked)
            // Ninjas rule
        break;
}
}
Aminoplast answered 22/1, 2017 at 7:45 Comment(0)
E
0

If you want to see which radio Button is checked or selected in the radio group then use the following:

//1. declare the radio group and the radio Button in the java file.
RadioGroup radiobtn;
RadioButton radio;
Button btnClick;
 //the radio is the element of the radiogroup which will assigned when we select the radio button
 //Button to trigger the toast to show which radio button is selected of the radio group


//2. now define them in the java file
radiobtn = findViewById(R.id.radiobtn);
btnClick = findViewById(R.id.btnClick);
 //we are instructing it to find the elements in the XML file using the id


//3. Now Create an on Click listener for the button
btnClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int selectedId = radiobtn.getCheckedRadioButtonId();
             //we are defining the selectId and then we are fetching the id of the checked radio button using the function getCheckedRadioButton()
            radio = findViewById(selectedId);
             //now the radioButton object we have defined will come into play, we will assign the radio to the radio button of the fetched id of the radio group
            Toast.makeText(MainActivity.this,radio.getText(),Toast.LENGTH_SHORT).show();
             //we are using toast to display the selected id of the radio button
             //radio.getText() will fetch the id of the radio Button of the radio group
        }
    });
Evangelical answered 23/9, 2019 at 14:8 Comment(0)
R
0

My MainActivity.java

package com.example.endsempracmad;

import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
String selection;

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

    ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle("Home Activity");

    RadioGroup radioGroup = findViewById(R.id.my_radio_group);




    Button myButton = findViewById(R.id.button);

    myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Create an intent to start the new activity
            Intent intent = new 
 Intent(MainActivity.this,SecondActivity.class);
            int selectedId = radioGroup.getCheckedRadioButtonId();
            if(selectedId != -1){
                RadioButton selectedRadioButton = findViewById(selectedId);
                selection = selectedRadioButton.getText().toString();


            }
            intent.putExtra("selection", selection);
            startActivity(intent);

            // Start the new activity
            startActivity(intent);
        }
    });

    //Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show();

}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout             
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

 <Button
    android:id="@+id/button"
    android:layout_width="267dp"
    android:layout_height="123dp"
    android:layout_marginStart="45dp"
    android:layout_marginTop="450dp"
    android:layout_marginEnd="99dp"
    android:layout_marginBottom="158dp"
    android:text="Button"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

 <RadioGroup
    android:id="@+id/my_radio_group"
    android:layout_width="166dp"
    android:layout_height="248dp"
    android:layout_marginStart="34dp"
    android:layout_marginTop="129dp"
    android:layout_marginEnd="211dp"
    android:layout_marginBottom="354dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="69dp"
        android:background="@drawable/messi"
        android:text="Radio button 1" />

    <RadioButton
        android:layout_width="120dp"
        android:layout_height="81dp"
        android:background="@drawable/messi"
        android:text="Radio button 2" />

    <RadioButton
        android:layout_width="123dp"
        android:layout_height="84dp"
        android:background="@drawable/messi"

        android:text="Radio button 3" />
</RadioGroup>


</androidx.constraintlayout.widget.ConstraintLayout>

secondActivity.java

package com.example.endsempracmad;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {

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

    String selection = getIntent().getStringExtra("selection");
    TextView textView = findViewById(R.id.textView);
    textView.setText("Selected option: " + selection);

}
}

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView"
    tools:layout_editor_absoluteX="212dp"
    tools:layout_editor_absoluteY="113dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Ravenravening answered 11/5, 2023 at 21:0 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Printmaker

© 2022 - 2024 — McMap. All rights reserved.