Can't set OnCheckedChangeListener to a Checkbox

前端 未结 3 1164
傲寒
傲寒 2021-01-02 01:01

I am trying to set a OnCheckedChangeListener to a CheckBox but my application exits in the run time. I also tried to set listeners for my Tex

3条回答
  •  执笔经年
    2021-01-02 01:03

    Implement CheckBox Listener for your class this way, especially if you have more than one CheckBox to deal with, you can handle in switch case blocks and makes your code neater:

     public class MyClass extends AppCompatActivity implements
        CompoundButton.OnCheckedChangeListener,{
    
          CheckBox myCheckBox;
      }
    

    In your onCreate() method put this:

        myCheckBox = (CheckBox)findViewById(R.Id.myCheckBoxName_in_XML_layout);
        mmyCheckBox.setOnCheckedChangeListener(this);
    

    Listern for your checkbox view event like this:

      @Override
       public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    
        switch (buttonView.getId()){
            case R.id.myCheckBoxName_in_XML_layout:
    
                if(isChecked == true) {
                    Toast.makeText(this, "Checked", Toast.LENGTH_SHORT).show();
                } else{
                        Toast.makeText(this, "Unchecked", Toast.LENGTH_SHORT).show();
                       }
    
                break;
             }
    
          }
    

提交回复
热议问题