4

I have an issue like selecting and unselecting a single radio button on click, the setOnCheckChangeListner() works only for the first time below is the code which I have tried.

radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
           @Override
           public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
               if(isChecked) radioButton.setChecked(false);
               else radioButton.setChecked(true);
           }
       });
Vikas Jain
  • 73
  • 1
  • 8

3 Answers3

11

I have made a solution for it using set selected attribute of the radio button.

final RadioButton radioButton = findViewById(R.id.radioButton);
        radioButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!radioButton.isSelected()) {
                    radioButton.setChecked(true);
                    radioButton.setSelected(true);
                } else {
                    radioButton.setChecked(false);
                    radioButton.setSelected(false);
                }
            }
        });
avez raj
  • 2,055
  • 2
  • 22
  • 37
1

You are generating a endless loop. That will cause stackoverflow error.

Because you are changing radio button checked status inside onCheckedChanged.

If you need changing check status then do it in click of a button.

Don't change check status inside onCheckedChanged

Perhaps you need to change status of RadioButton for some condition. For that you will do following.

public class MainActivity extends AppCompatActivity {
    RadioButton radioButton = null;
    CompoundButton.OnCheckedChangeListener listener;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO: 8/6/2018 your logics 
            }
        };
        radioButton.setOnCheckedChangeListener(listener);

        changeStatus(radioButton, true);
    }

    private void changeStatus(RadioButton radioButton, boolean status){
        radioButton.setOnCheckedChangeListener(null);
        radioButton.setChecked(status);
        radioButton.setOnCheckedChangeListener(listener);
    }
}

When you need to change status then call

changeStatus(radioButton, true);
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
1

try to use preference xml this one is essay to save the click events.because its like small db.
How to create RadioButton group in preference.xml window?