Android开发:点击RadioButton后如何禁用指定EditText?
需求说明
选中不同RadioButton时,控制EditText的启用状态:
- 选中「Islam」时,两个EditText都禁用
- 选中「Christian」时,启用
txtchristian、禁用txtothers - 选中「Others」时,启用
txtothers、禁用txtchristian
XML布局(使用RadioGroup分组)
<RadioGroup android:id="@+id/religion_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:text="Religion" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <RadioButton android:id="@+id/islam" android:text="Islam" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <RadioButton android:id="@+id/christian" android:text="Christian" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <EditText android:id="@+id/txtchristian" android:hint="pls specify" android:inputType="text" android:layout_width="match_parent" android:layout_height="wrap_content"/> <RadioButton android:id="@+id/others" android:text="Others" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <EditText android:id="@+id/txtothers" android:hint="pls specify" android:inputType="text" android:layout_width="match_parent" android:layout_height="wrap_content"/> </RadioGroup>
核心逻辑代码
if(islam.isChecked()){ txtothers.setEnabled(false); txtchristian.setEnabled(false); } else if(christian.isChecked()){ txtothers.setEnabled(false); txtchristian.setEnabled(true); } else{ txtothers.setEnabled(true); txtchristian.setEnabled(false); }
完整实现建议(绑定RadioGroup监听)
把逻辑绑定到RadioGroup的选中监听上,实现自动响应选中变化:
// 初始化控件 RadioGroup religionGroup = findViewById(R.id.religion_group); EditText txtchristian = findViewById(R.id.txtchristian); EditText txtothers = findViewById(R.id.txtothers); // 设置选中监听 religionGroup.setOnCheckedChangeListener((group, checkedId) -> { switch (checkedId) { case R.id.islam: txtchristian.setEnabled(false); txtothers.setEnabled(false); break; case R.id.christian: txtchristian.setEnabled(true); txtothers.setEnabled(false); break; case R.id.others: txtchristian.setEnabled(false); txtothers.setEnabled(true); break; } }); // 初始化界面默认状态(以默认选中Islam为例) txtchristian.setEnabled(false); txtothers.setEnabled(false);
内容的提问来源于stack exchange,提问作者kenneth
相关产品推荐
相关产品推荐

