Android 之 复选框(CheckBox)的使用

1.调用setOnCheckedChangeListener()方法,并把 CompoundButton.OnCheckedChangeListener实例作为参数传入
2.在CompoundButton.OnCheckedChangeListener的onCheckedChanged()方法里,取得被选中复选框的实例

/** Called when the activity is first created. */
private CheckBox c1,c2 ;
private Button button;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
c1 = (CheckBox) findViewById(R.id.CheckBox01);
c2 = (CheckBox) findViewById(R.id.CheckBox02);
button = (Button) findViewById(R.id.Button01);

//注册事件监听
c1.setOnCheckedChangeListener(new CheckBoxListener());
c2.setOnCheckedChangeListener(new CheckBoxListener());
button.setOnClickListener(new ButtonClickListener());

}

//定义事件
class CheckBoxListener implements OnCheckedChangeListener{
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
//Toast
Toast.makeText(CheckBoxActivity.this, buttonView.getText()+"被选择",Toast.LENGTH_SHORT ).show();
}else{
Toast.makeText(CheckBoxActivity.this, buttonView.getText()+"取消选择",Toast.LENGTH_SHORT ).show();
}
}
}

class ButtonClickListener implements OnClickListener{
String buffer = "";
public void onClick(View v) {
if(c1.isChecked())
buffer = buffer+c1.getText();
if(c2.isChecked())
buffer = buffer +c2.getText();
Toast.makeText(CheckBoxActivity.this, buffer+"被选择", Toast.LENGTH_SHORT).show();
}
}


[b]main.xml[/b]

<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>

<CheckBox android:text="金钱" android:id="@+id/CheckBox01" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
<CheckBox android:text="地位" android:id="@+id/CheckBox02" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
<Button android:id="@+id/Button01" android:text="确定" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>


[b]运行效果[/b]
[img]http://dl.iteye.com/upload/attachment/315087/39396fdd-91d6-3146-9da0-d2c43df181e4.png[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值