How to check if android checkbox is checked within its onClick method (declared in XML)?

后端 未结 5 1504
终归单人心
终归单人心 2020-12-05 03:41

I have a checkbox in android which has the following XML:



        
5条回答
  •  余生分开走
    2020-12-05 04:38

    @BindView(R.id.checkbox_id) // if you are using Butterknife
    CheckBox yourCheckBox;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_activity); 
        yourCheckBox = (CheckBox)findViewById(R.id.checkbox_id);// If your are not using Butterknife (the traditional way)
    
        yourCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                yourObject.setYourProperty(yourCheckBox.isChecked()); //yourCheckBox.isChecked() is the method to know if the checkBox is checked
                Log.d(TAG, "onClick: yourCheckBox = " + yourObject.getYourProperty() );
            }
        });
    }
    

    Obviously you have to make your XML with the id of your checkbox :

    
    

    So, the method to know if the check box is checked is : (CheckBox) yourCheckBox.isChecked() it returns true if the check box is checked.

提交回复
热议问题