复选框CheckBox

public class MainActivity extends Activity {
    private CheckBox[] checks;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 找出对应的控件
        checks = new CheckBox[3];
        checks[0] = (CheckBox) findViewById(R.id.check0);
        checks[1] = (CheckBox) findViewById(R.id.check1);
        checks[2] = (CheckBox) findViewById(R.id.check2);
    }

    // 点击按钮时调用该方法
    public void btn_click(View view) {
        // 遍历checks数组 找出选中项
        String result = "";
        for(CheckBox check : checks) {
            if(check.isChecked()) {
                result += check.getText().toString() + " ";
            }
        }
        Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
    }
}



@Override//复选框改变事件
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  //CompoundButton buttonView, 表示改变的控件
  //boolean isChecked 表示改变的控件的改变的后值
}

 

布局文件:

<LinearLayout 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:orientation="vertical"
    tools:context="com.example.day04_checkbox.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="前方有妖怪,派谁出战" />

    <CheckBox
        android:id="@+id/check0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="孙" />

    <CheckBox
        android:id="@+id/check1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="猪" />

    <CheckBox
        android:id="@+id/check2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="沙" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="btn_click"
        android:text="确定" />

</LinearLayout>

 修改默认的样式,替换成自己的图片

<CheckBox
                android:id="@+id/cb_circle_join"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_marginRight="20dp"
                android:button="@drawable/selector_cricle_join"/>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@mipmap/myjoin" android:state_checked="false" />
    <item android:drawable="@mipmap/mytuichu" android:state_checked="true" />
</selector>

 

posted @ 2016-06-04 13:11  ts-android  阅读(461)  评论(0编辑  收藏  举报