android CheckBox控件的定义及事件监听,本例实现CheckBox控件的定义及点击事件的监听并显示结果,运行效果截图如下:
CheckBox控件的定义,main.xml内容如下:
01
<?xml version="1.0" encoding="utf-8"?>
02
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
03
android:orientation="vertical"
04
android:layout_width="fill_parent"
05
android:layout_height="fill_parent"
06
>
07
<EditText
08
android:id="@+id/editText1"
09
android:layout_width="fill_parent"
10
android:layout_height="wrap_content"
11
android:text="请选择"
12
/>
13
<CheckBox
14
android:id="@+id/beijing"
15
android:layout_width="wrap_content"
16
android:layout_height="wrap_content"
17
android:text="北京"
18
/>
19
<CheckBox
20
android:id="@+id/shanghai"
21
android:layout_width="wrap_content"
22
android:layout_height="wrap_content"
23
android:text="上海"
24
/>
25
<CheckBox
26
android:id="@+id/shenzhen"
27
android:layout_width="wrap_content"
28
android:layout_height="wrap_content"
29
android:text="深圳"
30
/>
31
</LinearLayout>
activity CheckBoxTest.java内容如下:
01
package checkbox.pack;
02
03
import android.app.Activity;
04
import android.os.Bundle;
05
import android.widget.CheckBox;
06
import android.widget.CompoundButton;
07
import android.widget.EditText;
08
09
public class CheckBoxTest extends Activity {
10
/** Called when the activity is first created. */
11
//对控件对象进行声明
12
CheckBox beijing=null;
13
CheckBox shanghai=null;
14
CheckBox shenzhen=null;
15
EditText editText1=null;
16
@Override
17
public void onCreate(Bundle savedInstanceState) {
18
super.onCreate(savedInstanceState);
19
setContentView(R.layout.main);
20
//通过控件的ID来得到代表控件的对象
21
beijing=(CheckBox)findViewById(R.id.beijing);
22
shanghai=(CheckBox)findViewById(R.id.shanghai);
23
shenzhen=(CheckBox)findViewById(R.id.shenzhen);
24
editText1=(EditText)findViewById(R.id.editText1);
25
//给CheckBox设置事件监听
26
beijing.setOnCheckedChangeListener(newCompoundButton.OnCheckedChangeListener(){
27
@Override
28
public void onCheckedChanged(CompoundButton buttonView,
29
boolean isChecked) {
30
// TODO Auto-generated method stub
31
if(isChecked){
32
editText1.setText(buttonView.getText()+"选中");
33
}else{
34
editText1.setText(buttonView.getText()+"取消选中");
35
}
36
}
37
});
38
shanghai.setOnCheckedChangeListener(newCompoundButton.OnCheckedChangeListener(){
39
@Override
40
public void onCheckedChanged(CompoundButton buttonView,
41
boolean isChecked) {
42
// TODO Auto-generated method stub
43
if(isChecked){
44
editText1.setText(buttonView.getText()+"选中");
45
}else{
46
editText1.setText(buttonView.getText()+"取消选中");
47
}
48
}
49
});
50
shenzhen.setOnCheckedChangeListener(newCompoundButton.OnCheckedChangeListener(){
51
@Override
52
public void onCheckedChanged(CompoundButton buttonView,
53
boolean isChecked) {
54
// TODO Auto-generated method stub
55
if(isChecked){
56
editText1.setText(buttonView.getText()+"选中");
57
}else{
58
editText1.setText(buttonView.getText()+"取消选中");
59
}
60
}
61
});
62
}
63
}
注意CheckBoxTest.java 第26行CheckBox的事件实现通过CompoundButton.OnCheckedChangeListener来实现。