Question

how can i make button clickable after checking two check boxes in android

<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ok1" />

<CheckBox
    android:id="@+id/checkBox2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ok2" />


<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start" />

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final CheckBox ch1 = (CheckBox)findViewById(R.id.checkBox1);
    final CheckBox ch2 = (CheckBox)findViewById(R.id.checkBox2);
    final Button start = (Button)findViewById(R.id.button1);
    if(ch1.isChecked() && ch2.isChecked()){
        start.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_LONG);
            }

        });
    }
}

i am new to programming

thanks in advance

Was it helpful?

Solution

Use Button.setEnabled(Boolean) to control if the button is clickable or not. Then create an OnCheckedChangeListener for the checkboxes. These are used to react to a change in the checkboxes. Within the listener, check if the checkboxes are both checked. If they are, enable the button. Otherwise, if the button is enabled, disable it.

Also, enabling and disabling the button will cause it to be grey when disabled. You can also use setClickable if you do not want an appearance change for the button

final Button b = (Button)findViewById(R.id.button1);
b.setEnabled(false);
final CheckBox cb1 = (CheckBox)findViewById(R.id.checkBox1);
final CheckBox cb2 = (CheckBox)findViewById(R.id.checkBox2);
OnCheckedChangeListener checker = new OnCheckedChangeListener(){ 

    @Override
    public void onCheckedChanged(CompoundButton cb, boolean b) {
        if(cb1.isChecked()&&cb2.isChecked()){
            b.setEnabled(true);
        }
        else if(b.isEnabled()){
            b.setEnabled(false);
        }

    }

};
cb1.setOnCheckedChangeListener(checker);
cb2.setOnCheckedChangeListener(checker);
b.setOnClickListener(new OnClickListener(){

    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "It Worked", Toast.LENGTH_SHORT).show();
    }

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top