Selection Controls 3: CheckBox and RadioButton

Public on April 9, 2010
CheckBox:

The check box has two states: Checked and UnChecked. It inherits from TextView so it has all of its properties:
<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/txt"
/>
<CheckBox
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/Chk"
android:text="This is a check box"
android:checked="false"

/>
</LinearLayout>



and to handle the check/uncheck event:
CheckBox chk=(CheckBox)findViewById(R.id.Chk);
chk.setOnCheckedChangeListener(new OnCheckedChangeListener()
{

public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
TextView txt=(TextView)findViewById(R.id.txt);
if (arg1)
txt.setText("checked");
else
txt.setText("Unchecked");

}

}
);


RadioButton:
Android provides Radio button control. You create a RadioGroup and add RadioButtons inside it.
<?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"
>
<TextView
android:id="@+id/txt"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<RadioGroup
android:id="@+id/group"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Radio Group"
>
<RadioButton android:id="@+id/item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item1"
android:checked="true"
/>
<RadioButton android:id="@+id/item2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item2" />
<RadioButton android:id="@+id/item3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item3" />
</RadioGroup>
</LinearLayout>




You can get the checked item from code like this:
RadioGroup rg=(RadioGroup)findViewById(R.id.group);
rg.setOnCheckedChangeListener(new android.widget.RadioGroup.OnCheckedChangeListener()
{

public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.txt);
RadioButton rb=(RadioButton)findViewById(arg1);
txt.setText("You selected "+rb.getText());

}

}
);





[Advertising]Faster Thinking - Speed up your brain


Faster Thinking Game



sentiment_satisfied Emoticon