本例子是对checkbox组件的小练习。用4个checkbox供选择今天吃什么食物。通过button点击确定后弹出提示对话框,提示选中的食物。
主要应用了isChecked()方法。如果被勾选,则加入字符串中。
布局文件:checkbox_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="6dp" >
<TextView
android:id="@+id/tv_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="16dp"
android:paddingTop="16dp"
android:text="今天要吃的食物有:" />
<CheckBox
android:id="@+id/cb_red_row"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="红烧肉" />
<CheckBox
android:id="@+id/cb_noodles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="拉面" />
<CheckBox
android:id="@+id/cb_checken"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="鸡排饭" />
<CheckBox
android:id="@+id/cb_cai_jiao_eggs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="菜椒蒸鸡蛋" />
<Button
android:id="@+id/btn_submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="submit"
android:text="提交" />
</LinearLayout>
AtyCheckBox.java文件:
package com.fxj.composit;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import com.fxj.compractice.R;
public class AtyCheckBox extends Activity {
private CheckBox redRow, noodles, checken, caiJiaoEggs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkbox_layout);
// 实例化控件
caiJiaoEggs = (CheckBox) findViewById(R.id.cb_cai_jiao_eggs);
redRow = (CheckBox) findViewById(R.id.cb_red_row);
noodles = (CheckBox) findViewById(R.id.cb_noodles);
checken = (CheckBox) findViewById(R.id.cb_checken);
}
// Button监听事件
public void submit(View view) {
String str = "今天吃的食物有:\n";
if (redRow.isChecked()) {
str += "红烧肉\n";
}
if (noodles.isChecked()) {
str += "拉面\n";
}
if (checken.isChecked()) {
str += "鸡排饭\n";
}
if (caiJiaoEggs.isChecked()) {
str += "菜椒蒸鸡蛋\n";
}
// 弹出提示对话框
new AlertDialog.Builder(this).setTitle("结果").setMessage(str)
.setPositiveButton("确定", null).show();
}
}
运行效果: