flips the checkbox to unchecked if it was checked : CheckBox « UI « Android






flips the checkbox to unchecked if it was checked

 

package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;

public class Test extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    CheckBox fishCB = (CheckBox) findViewById(R.id.fishCB);

    if (fishCB.isChecked())
      fishCB.toggle();

    fishCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

      public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
        Log.v("CheckBoxActivity", (isChecked ? "checked" : "not checked"));
      }
    });
  }

  public void doClick(View view) {
    Log.v("CheckBoxActivity", ((CheckBox) view).isChecked() ? "checked" : "not checked");
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">

<CheckBox android:id="@+id/chickenCB"  android:text="Chicken" android:checked="true"
    android:layout_width="wrap_content" android:layout_height="wrap_content" />

<CheckBox android:id="@+id/fishCB"  android:text="Fish"
    android:layout_width="wrap_content" android:layout_height="wrap_content" />

<CheckBox android:id="@+id/steakCB"  android:text="Steak" android:checked="true"
    android:layout_width="wrap_content" android:layout_height="wrap_content" 
    android:onClick="doClick" />

</LinearLayout>

   
  








Related examples in the same category

1.Listen to CheckBox action
2.Is CheckBox selected
3.Get CheckBox value
4.Use choice mode on a list. This list is in CHOICE_MODE_SINGLE mode, which means the items behave like checkboxes.
5.Use choice mode on a list. This list is in CHOICE_MODE_MULTIPLE mode, which means the items behave like checkboxes.