androidandroid-checkboxoncheckedchanged

How to call function on android checkbox checked?


I have an activity, which contains 4 checkboxes. So my question is - when all these checkboxes are checked, I want a message to pop-up that should say something like "Good job!", so my question is how do I do it ?

Code of the activity

Code of the checkboxes


Solution

  • Add this code in your onCreate method.

    NOTE: You can use a checkbox array to short the code.

    But this will help you to understand what to do.

    First, you have to create checkbox variables in java file. Then set onCheckChanged listener to each checkbox.

    CheckBox cb1=(CheckBox)findViewById(R.id.checkBox);
    CheckBox cb2=(CheckBox)findViewById(R.id.checkBox2);
    CheckBox cb3=(CheckBox)findViewById(R.id.checkBox3);
    CheckBox cb4=(CheckBox)findViewById(R.id.checkBox4);
    
    cb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(cb1.isChecked()&&cb2.isChecked()&&cb3.isChecked()&&cb4.isChecked())
                Toast.makeText(getApplicationContext(),"Good job." , Toast.LENGTH_SHORT).show();
            
        }
    });
    
    cb2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(cb1.isChecked()&&cb2.isChecked()&&cb3.isChecked()&&cb4.isChecked())
                Toast.makeText(getApplicationContext(),"Good job." , Toast.LENGTH_SHORT).show();
            
        }
    });
    
    cb3.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(cb1.isChecked()&&cb2.isChecked()&&cb3.isChecked()&&cb4.isChecked())
                Toast.makeText(getApplicationContext(),"Good job." , Toast.LENGTH_SHORT).show();
            
        }
    });
    
    cb4.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(cb1.isChecked()&&cb2.isChecked()&&cb3.isChecked()&&cb4.isChecked())
                Toast.makeText(getApplicationContext(),"Good job." , Toast.LENGTH_SHORT).show();
            
        }
    });
    

    Insert this import statements before the class begin (public class flygos2..) . You can see there are other import statements are there also.

    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.CompoundButton.OnCheckedChangeListener;