Android CheckBox 的使用案例分析
public class mainactivity extends activity {
textview tv;
checkbox cb1;
checkbox cb2;
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
cb1 = (checkbox) findviewbyid(r.id.checkbox1);
cb2 = (checkbox) findviewbyid(r.id.checkbox2);
tv = (textview) findviewbyid(r.id.textview1);
cb1.setoncheckedchangelistener(cb);
cb2.setoncheckedchangelistener(cb);
}
private checkbox.oncheckedchangelistener cb = new checkbox.oncheckedchangelistener() {
@override
public void oncheckedchanged(compoundbutton buttonview, boolean ischecked) {
string stv = getstring(r.string.hoby);
string scb1 = getstring(r.string.basketball);
string scb2 = getstring(r.string.football);
if (cb1.ischecked() && cb2.ischecked()) {
tv.settext(stv + ":" + scb1 + "&&" + scb2);
} else if (cb1.ischecked() && !cb2.ischecked()) {
tv.settext(stv + ":" + scb1);
} else if (!cb1.ischecked() && cb2.ischecked()) {
tv.settext(stv + ":" + scb2);
} else {
tv.settext(stv);
}
}
};
如下是布局文件:
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<textview
android:id="@+id/textview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hoby" />
<checkbox
android:id="@+id/checkbox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/basketball" />
<checkbox
android:id="@+id/checkbox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/football" />
</linearlayout>