开发者

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

开发者_高级运维

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜