问题
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