android unchecked radio button which is already checked

Query picture Query · May 7, 2015 · Viewed 20.2k times · Source
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rg"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.radiogroup.MainActivity" >

    <RadioButton
        android:id="@+id/rb_true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_vertical" />

    <RadioButton
        android:id="@+id/rb_false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_vertical" />

</RadioGroup>

i have one radio group in which i have 2 radio button

now if radio button 1 is selected and if i tap on same radio button(radio button 1) it should be unchecked ..

it should work astoggle.

Answer

Deepika Rajani picture Deepika Rajani · May 7, 2015

This should serve the purpose.

radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {
    @Override
    public void onCheckedChanged(RadioGroup arg0, int id)
    {
    RadioButton checkedRadioButton = (RadioButton)radioGroup.findViewById(id);

    boolean isChecked = checkedRadioButton.isChecked();

    if (isChecked)
    {
    Toast.makeText(getApplicationContext(), 
               checkedRadioButton.getText(),Toast.LENGTH_LONG).show();
    radioButton = (String) checkedRadioButton.getText();
    checkedRadioButton.setChecked(false);
    }
    else
        checkedRadioButton.setChecked(true);
    }});

Also, don't forget to initialize RadioGroup