How to make UI components disappear when a certain RadioButton is selected

佐手、 提交于 2019-12-10 20:41:40

问题


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 selects RadioButton2 the DatePicker should disappear from the screen.

How can I handle the scenario? Should I make the change in layout / Java code?


回答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.



来源:https://stackoverflow.com/questions/4850238/how-to-make-ui-components-disappear-when-a-certain-radiobutton-is-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!