How to make UI components disappear when you select a specific RadioButton

I created an xml layout file in which I have two RadioButtons.

By default, RadioButton1 is selected and the component is displayed on the screen DatePicker, but when the user selects RadioButton2, it DatePickershould disappear from the screen.

How can I handle the script? Should I make changes to the Java layout / code?

+3
source share
1 answer

This is actually very simple.

Get a link to RadioGroupand DatePicker. Contribute OnCheckedChangeListenerfor RadioGroupand check where it was marked RadioButton.

RadioButton A, DatePicker , RadioButton B, gone invisible .

.

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

    }
}

- .

+5

Source: https://habr.com/ru/post/1788960/


All Articles