【问题标题】:why checkbox listener method called not working?为什么复选框侦听器方法调用不起作用?
【发布时间】:2021-11-30 07:31:44
【问题描述】:

在下面的代码中,我希望仅在单击复选框时才调用 afterscan 方法。但是有些我注意到一旦选中该方法,就会从所有其他复选框中调用该方法。任何帮助将不胜感激

Chk_class 类实现 CompoundButton.OnCheckedChangeListener{

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        result=new StringBuilder();

        if(checkBox2.isChecked())
        {
            result.append("Connection issue |");
        }
  
        if(checkBox4.isChecked())
        {
            result.append("Machnical issue |");
        }
        Toast toast = Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
        liftError=result.toString();

        if(checkBoxer.isChecked()){

            afterscan();  // this method is called from all other checkbox as well 
        }


    }
}

【问题讨论】:

  • 也许检查buttonView 是否为checkBoxer(如果所有复选框都使用相同的侦听器)

标签: java android checkbox


【解决方案1】:

如果您对所有复选框都使用此方法,那么您可以执行以下操作(这不是一种干净的方法,但应该可以解决问题):

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

     .... 

    if(checkBoxer.isChecked()&&checkBoxer.getId()==buttonView.getId()){
        afterscan();  
    }


  }   

【讨论】:

    【解决方案2】:
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    
         .... 
    
        if(checkBoxer.isChecked()&&checkBoxer.getId()==buttonView.getId()){
            afterscan();  
        }
    } 
    

    【讨论】:

    • 虽然此代码 sn-p 可能会解决问题,但including an explanation 将帮助人们了解您的代码建议的原因。
    猜你喜欢
    • 1970-01-01
    • 2013-02-07
    • 2011-03-31
    • 2019-02-27
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    相关资源
    最近更新 更多