首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用onCheckedChanged设置多个复选框的事件

使用onCheckedChanged设置多个复选框的事件
EN

Stack Overflow用户
提问于 2017-05-09 09:12:46
回答 1查看 1.8K关注 0票数 1

我的登录复选框有问题。

首先,我将为每个复选框创建3个复选框并创建更改监听器。

代码语言:javascript
复制
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

private CheckBox main_id_saver;
private CheckBox main_pw_saver;
private CheckBox main_auto_login;

并在onCreate中为每个wiget分配ID (跳过xml文件)

代码语言:javascript
复制
main_id_saver = (CheckBox) findViewById(R.id.main_id_saver);
main_pw_saver = (CheckBox) findViewById(R.id.main_pw_saver);
main_auto_login = (CheckBox) findViewById(R.id.main_auto_login);

main_id_saver.setOnCheckedChangeListener(this);
main_pw_saver.setOnCheckedChangeListener(this);
main_auto_login.setOnCheckedChangeListener(this);

我想为下面满足的复选框设置一个单击事件

  1. 如果选中ID,PW复选框,那么自动登录复选框将被自动选中。
  2. 不能只选中PW复选框
  3. 如果自动登录被选中,那么ID,PW会自动检查。
  4. 如果在所有复选框的状态中单击任何复选框,则将取消选中所有复选框。

我做了一些尝试,下面是

代码语言:javascript
复制
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (main_auto_login.isChecked()){
        if(!main_id_saver.isChecked() || !main_pw_saver.isChecked()) {
            main_id_saver.setChecked(true);
            main_pw_saver.setChecked(true);
            return;
        } else if (main_id_saver.isChecked()&&main_pw_saver.isChecked()&&main_auto_login.isChecked()){
            main_auto_login.setChecked(false);
            main_id_saver.setChecked(false);
            main_pw_saver.setChecked(false);
            return;
        }
    } else if(main_pw_saver.isChecked()){
        if(main_id_saver.isChecked()){
            main_auto_login.setChecked(true);
            return;
        } else if(!main_id_saver.isChecked()){
            Toast.makeText(MainActivity.this, "CANNOT REMEMBER PASSWORD BUT FOR ID",Toast.LENGTH_SHORT).show();
            main_pw_saver.setChecked(false);
            return;
        }
    }
    return;
}

但这不像我想的那样有效

解决这个问题的最佳代码是什么?

在我傲慢的看法,把onChangedLinster事件分开是最好的答案,但我不能做到.

EN

回答 1

Stack Overflow用户

发布于 2017-05-09 09:17:38

代码语言:javascript
复制
chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (buttonView.getId()){
                case R.id.checkbox1:
                    if(isChecked)
                        //Do something
                    else
                        //Do something
                    break;
                case R.id.checkBox2:
                    if(isChecked)
                    //Do something
                    else
                    //Do something
                    break;


            }
        }
    });
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43865744

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档