Android CheckBox Code Snippets

Checkboxes allow the user to select one or more options from a set. Typically, you should present each checkbox option in a vertical list.To create a Checkbox we use Checkbox element in layout where as we use Checkbox object in java. To respond to clic event on a Checkbox add android: onClick attribute to the Checkbox element in your Xml.

XML Snippet

<CheckBoxandroid:id="@+id/checkbox_cheese"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cheese"
android:onClick="onCheckboxClicked"/>

CheckBox Method

1. Public void setChecked(boolean checked):
Changes the checked state of this button,param checked true to check the button, false to uncked it.

2.public booleanisCheced():
This method returns the status of Checkbox like checked or uncheked.If checked returns true,otherwise returns false.

Java Snippet for CheckBox

public class MainActivity extends Activity
    {
     CheckBox cb1[] = new CheckBox[4];
      CheckBox cb;
    int ids[] = {R.id.cb1,R.id.cb2,R.id.cb3,R.id.cb4};
     int counter;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     scb = (CheckBox)findViewById(R.id.scb1);
     for (inti=0;i<cb1· length;i++)
    {
      cb1[i] = (CheckBox)findViewById(ids[i]);
    }
    }
    public void displaySelectAll(View v)
    {
      CheckBox cb = (CheckBox)v;
      if(cb.isChecked())
    {
      for (int i=0;i<cb1· length;i++)
    {
      cb1[i].setChecked(true);
    }
    }
      else
    {
      for (int i=0;i<cb1· length;i++)
    {
      cb1[i].setChecked(false);
    }
    }
     public void displaySelectOne(View v)
    {
      CheckBox cb = (CheckBox)v;
     int id = cb.getId();
      switch (id)
    {
       case R.id.cb1:
    {
       if (cb.isChecked())
    {
       counter++;
    }
       break;
    }
      case R.id.cb2:
    {
      if (cb.isChecked())
    {
      counter++;
    }
      break;
    }
      case R.id.cb3:
    {
      if (cb.isChecked())
    {
      counter++;
    }
      break;
    }
      case R.id.cb4:
    {
      if (cb.isChecked())
    {
      counter++;
    }
    break;
    }
    }
      if (counter == 4)
    {
        scb.setChecked(true);
        counter=0;
    }
        else
        {
          scb.setChecked(false);
        }
    }
    }</cb1.length;i++)
    </cb1.length;i++)
    </cb1.length;i++)
See you in the next Android Code Snippet!
Comment via Facebook
0 Comment via Google

0 تعليقات:

Post a Comment