Search code examples
androidandroid-checkbox

Checkbox not enabled programatically in android


What i am doing:: I am having a checkbox and a button onclick of the button i am trying to enable the checkbox

What is happening:: Checkbox is not enabled onclick

Question:: How can i resolve my issue Is there any different approach to solve this


MainActivity.java

public class MainActivity extends Activity {

    Button button1;
    CheckBox checkBox1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1=(Button) findViewById(R.id.button1);
        checkBox1=(CheckBox) findViewById(R.id.checkBox1);

        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                checkBox1.setEnabled(true);
            }
        });
    }
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:checked="false"
        android:layout_marginTop="54dp"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/checkBox1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="67dp"
        android:text="Button" />

</RelativeLayout>

Solution

  • Try replacing your onClick code with the following:

    button1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            checkBox1.setChecked(true);
        }
    });
    

    I believe you were looking for setChecked(), not setEnabled().