Search code examples
androidandroid-checkbox

How to know if Checkbox is unchecked with a Button?


I am working on a registration activity where I validate to know if all the text fields have entered data and I have a checkbox where I want the user to accept terms and conditions.

Does anyone know how I can validate that the checkbox is unchecked on the button Onclicklistener?

Here is my code:

public class RegisterActivity extends AppCompatActivity {


private EditText userName, userMail, userPassword, userPassword2;
private Button btn_signUp;
private CheckBox cb_terms;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


    userName = (EditText)findViewById(R.id.userName);
    userMail = (EditText)findViewById(R.id.userMail);
    userPassword = (EditText)findViewById(R.id.userPassword);
    userPassword2 = (EditText)findViewById(R.id.userPassword2);
    btn_signUp = (Button)findViewById(R.id.btn_signUp);
    cb_terms = (CheckBox)findViewById(R.id.cb_terms);


    btn_signUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


            final String name = userName.getText().toString();
            final String mail = userMail.getText().toString();
            final String password = userPassword.getText().toString();
            final String password2 = userPassword2.getText().toString();


            if(name.isEmpty() || mail.isEmpty() || password.isEmpty() || !password.equals(password2)){


                showMessage("please check all the fields");

            }else {

                CreateUserAccount(mail,name,password);
            }

        }
    });

}

Solution

  • You can check for the value of your checkbox inside your click listener like like this :

    //this goes inside onClick
    
    if(cb_terms.isChecked()){ 
    //do something
    }