Skip to content Skip to sidebar Skip to footer

How To Make UI Components Disappear When A Certain RadioButton Is Selected

I have created a layout xml file where I have two RadioButtons. By default, RadioButton 1 is selected and I am displaying a DatePicker component on the screen but when the user sel

Solution 1:

It is actually very simple.

Get a reference of your RadioGroup and your DatePicker. Implement an OnCheckedChangeListener for the RadioGroup and check which RadioButton was checked in there.

If RadioButton A was checked set the visibility on your DatePicker to visible and if RadioButton B was checked set the visibility to gone or invisible depending on your requirement.

As an example.

public class MyActivity extends Activity {

    private RadioGroup choice;
    private DatePicker datePicker;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.your_layout);

        choice = (RadioGroup) findViewById(R.id.choice);
        datePicker = (DatePicker) findViewById(R.id.date_picker);

        choice.setOnCheckedChangeListener(
            new RadioGroup.OnCheckedChangeListener() {

            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId) {
                    case R.id.radio_button_a:
                        datePicker.setVisibility(View.VISIBLE);
                        break;
                    case R.id.radio_button_b:
                        datePicker.setVisibility(View.GONE);                    
                        break;
                }
            }
        });

    }
}

In theory it should be something like that.


Post a Comment for "How To Make UI Components Disappear When A Certain RadioButton Is Selected"