Android disable button when checkbox not checked

14,785

Solution 1

When you enter in that view make the button disabled (in your XML), and whenever user hit any of the check-boxes manage one global variable e.g if the global count is > 1 then make the button enable in that activity.

Manage the global variable in a way that if user is turning on the check box then increment it and if he is turning off the checkbox decrease the counter.

I hope you got the concept.

Basically it is all about managing the count how many checkboxes are turned on; if more then one is turned on make the button enabled else make it disabled.

Solution 2

Try with this,

 Button mButton=(Button)findViewById( R.id.button01);
    CheckBox mCheckBox= ( CheckBox ) findViewById( R.id.checkbox01);
    mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            if ( isChecked )
            {
              mButton.setEnabled(true);

            }else{
  mButton.setEnabled(false);
}

        }
    });

Solution 3

Instead of enabling and disabling the button you can use setVisibility() method for button. In the following manner.

Button btn =(Button)findViewById( R.id.mybutton);
CheckBox checkBox= ( CheckBox ) findViewById( R.id.checkbox01);
mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if ( isChecked )
        {
          btn.setVisibility(VISIBLE);
        }
          else{
                btn.setVisibility(GONE);
               }
     }
});

By using this method you can set the visibility of your view.Your button will be visible only if checkBox is cheaked otherwise your button will not be visible.Let me know it works or not for you.

Share:
14,785
reson90
Author by

reson90

Updated on June 22, 2022

Comments

  • reson90
    reson90 about 2 years

    I have a multiple checkbox and a button. What should I do to disable the button if none of the checkbox is check and enable the button if it's checked?

  • VikramV
    VikramV over 10 years
    When I use this checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){...} in my code, I get this error The method setOnCheckedChangeListener(CompoundButton.OnCheckedChangeLis‌​tener) in the type CompoundButton is not applicable for the arguments (new OnCheckedChangeListener(){}) Any idea/help as to what I would be missing?