CheckBox.setChecked(true)::设置选中状态
CheckBox.getText()
android.widget.CompoundButton.OnCheckedChangeListener
setOnCheckedChangeListener()
例题:
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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="爱好"
android:textSize="20dp"/>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"
android:id="@+id/tableLayout
">
<TableRow>
<CheckBox
android:id="@+id/cb1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="游泳"/>
<CheckBox
android:id="@+id/cb2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="喝水"/>
</TableRow>
<TableRow>
<CheckBox
android:id="@+id/cb3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="吃饭"/>
<CheckBox
android:id="@+id/cb4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="睡觉"/>
</TableRow>
</TableLayout>
<Button
android:id="@+id/submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="提交" />
</LinearLayout>
Activity内容:
package cn.calss3g.activity;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class CheckBoxDemo extends Activity implements OnCheckedChangeListener{
private CheckBox cb1,cb2,cb3,cb4;
private ArrayList<CheckBox> list = new ArrayList<CheckBox>();
private Button submitBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkbox_layout);
findView();
}
private void findView(){
cb1 = (CheckBox) this.findViewById(R.id.cb1);
cb2 = (CheckBox) this.findViewById(R.id.cb2);
cb3 = (CheckBox) this.findViewById(R.id.cb3);
cb4 = (CheckBox) this.findViewById(R.id.cb4);
list.add(cb1);
list.add(cb2);
list.add(cb3);
list.add(cb4);
for(CheckBox cb: list){
cb.setOnCheckedChangeListener(this);
}
submitBtn = (Button) this.findViewById(R.id.submit);
submitBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String fav ="";
for(CheckBox cb : list){
if(cb.isChecked()){
fav +=cb.getText();
}
}
Log.i("TAG",fav);
}
});
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i("TAG",buttonView.getText().toString());
}
}
实现效果:
选择选项后:
提交后: