Selection Controls 3 CheckBox and RadioButton

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
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
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());

}

}
);

Related Posts by Categories

0 comments:

Post a Comment

Blog Archive

Powered by Blogger.