CheckBox控件实现选项的选中

1:设置控件属性

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <!-- 注意checkbox选中之后还可以进行取消 -->
    <CheckBox
        android:checked="false"
        android:id="@+id/checkBox3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="迪迪" />

</RelativeLayout>

2:找到这个控件,设置监听器,用内部类检测监听结果并执行相应内容

package com.Thinker.checkbox;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class MainActivity extends Activity {
    private CheckBox checkbox;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /**
         * 找到相应控件对象赋给这个引用
         */
        checkbox = (CheckBox) findViewById(R.id.checkBox3);
        /**
         * 设置监听事件
         */
        checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                // TODO Auto-generated method stub
                if(arg1){
                    /*
                     * 安卓支持System.out.println来打印文字,同时也有自己的打印方法,Log.i("tag", text);
                           也可以通过日志来打印,其中tag是一个标志,text是String类型的对象
                     */
                    String text = checkbox.getText().toString();
                    Log.i("tag", text);
                }
            }
        });
    }
    
}

 

转载于:https://www.cnblogs.com/rain-1/p/5148767.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值