android CheckBox控件的定义及事件监听,本例实现CheckBox控件的定义及点击事件的监听并显示结果,运行效果截图如下:
CheckBox控件的定义,main.xml内容如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <EditText android:id="@+id/editText1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="请选择" /> <CheckBox android:id="@+id/beijing" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="北京" /> <CheckBox android:id="@+id/shanghai" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="上海" /> <CheckBox android:id="@+id/shenzhen" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="深圳" /> </LinearLayout>
activity CheckBoxTest.java内容如下:
package checkbox.pack;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
public class CheckBoxTest extends Activity {
/** Called when the activity is first created. */
//对控件对象进行声明
CheckBox beijing=null;
CheckBox shanghai=null;
CheckBox shenzhen=null;
EditText editText1=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//通过控件的ID来得到代表控件的对象
beijing=(CheckBox)findViewById(R.id.beijing);
shanghai=(CheckBox)findViewById(R.id.shanghai);
shenzhen=(CheckBox)findViewById(R.id.shenzhen);
editText1=(EditText)findViewById(R.id.editText1);
//给CheckBox设置事件监听
beijing.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
editText1.setText(buttonView.getText()+"选中");
}else{
editText1.setText(buttonView.getText()+"取消选中");
}
}
});
shanghai.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
editText1.setText(buttonView.getText()+"选中");
}else{
editText1.setText(buttonView.getText()+"取消选中");
}
}
});
shenzhen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
editText1.setText(buttonView.getText()+"选中");
}else{
editText1.setText(buttonView.getText()+"取消选中");
}
}
});
}
}
注意CheckBoxTest.java 第26行CheckBox的事件实现通过CompoundButton.OnCheckedChangeListener 来实现。