You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:点击RadioButton后如何禁用指定EditText?

实现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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:35:22