63

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?

CJBS
  • 15,147
  • 6
  • 86
  • 135
Ryan
  • 9,821
  • 22
  • 66
  • 101

6 Answers6

140

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());
        }
    }
});
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
A. Abiri
  • 10,750
  • 4
  • 30
  • 31
  • it says: "The local variable rgroup may not have been initialized" – Ryan Jul 21 '11 at 19:10
  • 4
    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); – A. Abiri Jul 21 '11 at 19:12
  • 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? – Ryan Jul 21 '11 at 19:18
  • 1
    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. – A. Abiri Jul 21 '11 at 19:41
  • 1
    That worked perfectly and also taught me how its all "wired" up in the back, thank you so much! – Ryan Jul 21 '11 at 19:46
  • I never quite got how this worked before, but your sample code and comments made the lightbulb turn on at last – sXe Jan 21 '15 at 02:32
21

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. ;)

Leo DroidCoder
  • 14,527
  • 4
  • 62
  • 54
PravinCG
  • 7,688
  • 3
  • 30
  • 55
  • 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 :( – Ryan Jul 21 '11 at 19:14
  • CheckedId is the id of the radiobutton that got clicked in the group. You need to use findViewbyId to make sense out of it. – PravinCG May 28 '14 at 05:15
  • 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. – Frank Schwieterman Nov 14 '16 at 21:02
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;
        }
      }
    });
Diego Venâncio
  • 5,698
  • 2
  • 49
  • 68
  • 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. – Luís Henriques Jun 28 '21 at 13:04
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;
}
}
Bellerofont
  • 1,081
  • 18
  • 17
  • 16
TheSwiftGuy77
  • 656
  • 1
  • 9
  • 25
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
        }
    });
Alex Ed
  • 41
  • 2
  • 9
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>
hee
  • 1
  • 1
  • 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](/help/how-to-answer). – Community May 12 '23 at 04:11