使用CheckBox实现多选效果

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

package com.example.checkboxdemo;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
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.checkBox1);
        //通过设置CheckBox的监听事件来对CheckBox是不是被选中
        checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
            
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1)
            {
                Log.i("tag", arg1+"");
                // 通过onCheckedChangeListener来监听当前的CheckBox是否被选中
                if(arg1){
                    //获得CheckBox的文本内容
                    String string =checkBox.getText().toString();
                    Log.i("tag", string);
                }
                
            }
        });
    }

}
<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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="28dp"
        android:text="篮球" />

</RelativeLayout>

 

posted @ 2016-03-03 21:07  沉默的羊癫疯  阅读(321)  评论(0编辑  收藏  举报