【问题标题】:How to make checkbox2 uncheck when checking checkbox1 and vice versa on AndroidStudio?在Android Studio上选中复选框1时如何取消选中复选框,反之亦然?
【发布时间】:2015-01-22 07:46:38
【问题描述】:

如何使复选框取消选中以前选中的复选框,反之亦然。我正在尝试开发一个应用程序,在其中检查您只能选择两个选项之一。我似乎无法让 onCheckedChangeListener 工作。我不想要单选按钮,因为它们不能被取消点击。

我尝试了 Noob 在类似问题下发布的这段代码。 I need to uncheck a checkbox when a particular checkbox is checked

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_setalarm);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    final CheckBox chk1 = (CheckBox) findViewById(R.id.checkBox1);
    final CheckBox chk2 = (CheckBox) findViewById(R.id.checkBox2);

    chk1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            chk2.setChecked(false);
        }
    });
    chk2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            chk1.setChecked(false);
        }
    });
}

【问题讨论】:

  • 为了让onCheckedChangeListener 正常工作,您做了哪些尝试?可以发一些代码吗?
  • 我添加了一个指向我尝试过的代码的链接。
  • 您尝试的代码有什么问题?你看到错误了吗?事件根本没有触发吗?将您的代码粘贴到问题中,以便我们尝试更好地帮助您。

标签: android checkbox


【解决方案1】:

如果您确定不想使用 RadioButtons 并且只有两个可能的 CheckBox 选项,像这样简单的东西应该可以解决问题:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_name);

    final CheckBox c1 = (CheckBox) findViewById(R.id.c1);
    final CheckBox c2 = (CheckBox) findViewById(R.id.c2);

    c1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            c2.setChecked(false);
            c1.setChecked(b);
        }
    });
    c2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            c1.setChecked(false);
            c2.setChecked(b);
        }
    });
}

【讨论】:

  • 快速提问,我是编码新手,你所说的实现逻辑是什么意思?
  • bonCheckChanged 中的值告诉你CheckBox 是否被选中。当其中一个CheckBoxes 的值发生更改时,也许您想做点什么?就像显示一个对话框。这就是我所说的“实现逻辑”。
  • 您能否举一个我可以填写的代码示例,例如 textview。或者我可以让它什么都不做吗?另外,除了c2.setChecked(false)之外,一切看起来都不错,c2在c1.setChecked(false)中的c1同样带有红色下划线,这是因为我没有实现b的值吗?
  • 您不必对if (b) 语句执行任何操作,如果您在选中/取消选中CheckBox 时不需要执行任何操作,则可以将其删除。关于红色曲线;这是因为您正在从内部类中访问c1c2 的值,您应该将它们声明为final。我已经适当地更新了我的答案。
  • 谢谢!我只是尝试运行应用程序,但是每当我尝试单击复选框时,应用程序就会崩溃!我用你给我的我尝试输入的代码更新了我的帖子。也许你知道它为什么会崩溃?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
  • 2014-04-05
  • 1970-01-01
  • 2019-02-28
相关资源
最近更新 更多