Android之多选按钮CheckBox

1,两种状态:选中状态(true),未选中状态(false)

2,重要属性:

android:checked="false"//当前CheckBox是否被选中,默认为false

3,layout布局中的代码:

<span style="font-size:18px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="请选择你的爱好:" 
        android:textSize="20sp">
    </TextView>

<CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginRight="22dp"
        android:layout_marginTop="30dp"
        android:checked="false" //默认为false,可以省略不写
        android:text="音乐" />

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/checkBox1"
        android:layout_marginTop="39dp"
        android:checked="false"
        android:text="体育" />
</RelativeLayout></span>


4,java类中的代码:

<span style="font-size:18px;">public class MainActivity extends Activity {

	private CheckBox checkBox1, checkBox2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// 初始化CheckBox控件
		checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
		checkBox2 = (CheckBox) findViewById(R.id.checkBox2);

		// 设置监听事件
		checkBox1.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {

				// 通过onCheckedChanged来监听当前的checkBox是否被选中
				if (isChecked) {
					String text = checkBox1.getText().toString();
					// 在LogCat中打印输出选中的文本信息
					Log.i("tag", text);
				}
			}
		});
		checkBox2.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {

				if (isChecked) {
					String text = checkBox2.getText().toString();
					Log.i("tag", text);
				}
			}
		});
	}
}</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值