【问题标题】:How to check condition using checkbox?如何使用复选框检查条件?
【发布时间】:2015-03-20 18:44:00
【问题描述】:

我正在尝试使用 json 向服务器发送值,我正在尝试的是当我选择复选框时我想发送“Y”,在我的 json 中 active=Y 是用户激活和停用的状态,以下是代码我试过了,但它不起作用,它总是显示 active=N

 proactives=(CheckBox)findViewById(R.id.edt_proactive);
     if(proactives.isChecked()==true)
      {
          proactives.setTag("Y");
      }
      if(proactives.isChecked()==false)
      {
          proactives.setTag("N");
      }

【问题讨论】:

标签: android android-checkbox


【解决方案1】:

试试这个

proactives.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(b)
            {
                proactives.setTag("Y");
            }
            if(proactives.isChecked()==false)
            {
                proactives.setTag("N");
            }
        }
    });

proactives.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
              proactives.setTag(b? "Y" : "N"); 
            }
        });

【讨论】:

  • proactives.isChecked()==true 不是必需的,因为 isChecked 已经返回一个布尔值,您正在将其与 true 进行比较。此外,由于 boolean b 表示检查的值,因此也不需要执行 actives.isChecked(),您可以将所有代码替换为 if (b) {...}else{...}
【解决方案2】:

使用CompoundButton.OnCheckedChangeListener

proactives.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

       @Override
       public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
           // use isChecked value here to react to state changes on your checkbox
       }
   }
);   

【讨论】:

【解决方案3】:

在布局文件中给予 onclick

<CheckBox
    android:id="@+id/edt_proactive"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="itemClicked" />

在你的活动中这样做

public void itemClicked(View v) {
    if (((CheckBox) v).isChecked()) {
        proactives.setTag("Y");
    }else{
        proactives.setTag("N");
}

【讨论】:

  • 但默认情况下我想设置取消选中我的复选框
  • 是的,它默认取消选中 android:onClick="itemClicked" 这行仅表示此复选框上的单击侦听器。
  • @2Dee 先生,您想修改此答案的内容
  • 答案的原始格式不正确,文本包含在代码块中,代码缩进也搞砸了,所以为了可读性我更正了它
  • @MdHussain 你能检查一下这个stackoverflow.com/questions/29183249/…
【解决方案4】:

你可以使用OnCheckedChangeListener

proactives.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // change your tag here
        }
    });

【讨论】:

    【解决方案5】:

    更快的方式:P

    proactives=(CheckBox)findViewById(R.id.edt_proactive);
    proactives.setTag(proactives.isChecked() ? "Y" : "N");
    

    编辑:并使用OnCheckedChangeListener 上述答案提及

    【讨论】:

    • 这如何回答这个问题?
    • 是的,它没有...我已经编辑了我的 ans,但已经有一个被接受的
    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2018-10-09
    • 2020-06-07
    • 1970-01-01
    • 2011-10-14
    • 2014-05-13
    相关资源
    最近更新 更多