Android基础控件——CheckBox多选框的全选功能

CheckBox多选框的全选功能


步骤一:CheckBox在xml中设置

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <CheckBox
        android:id="@+id/cb_java"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:text="java"
        android:textColor="#00f" />

    <CheckBox
        android:id="@+id/cb_php"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:text="php"
        android:textColor="#00f" />


    <CheckBox
        android:id="@+id/cb_c"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:text="C"
        android:textColor="#00f" />

    <CheckBox
        android:id="@+id/cb_all"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:text="全选"
        android:textColor="#00f" />

</LinearLayout>


步骤二:CheckBox在代码中使用

public class CheckBoxActivity extends Activity implements CompoundButton.OnCheckedChangeListener {

    CheckBox cb_java, cb_php, cb_c, cb_all;

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

        cb_java = (CheckBox) findViewById(R.id.cb_java);
        cb_php = (CheckBox) findViewById(R.id.cb_php);
        cb_c = (CheckBox) findViewById(R.id.cb_c);
        cb_all = (CheckBox) findViewById(R.id.cb_all);

        cb_java.setOnCheckedChangeListener(this);
        cb_php.setOnCheckedChangeListener(this);
        cb_c.setOnCheckedChangeListener(this);
        cb_all.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_all:
                if (isChecked) {
                    //全选
                    cb_all.setChecked(true);
                    cb_java.setChecked(true);
                    cb_php.setChecked(true);
                    cb_c.setChecked(true);
                } else {
                    //反选
                    cb_all.setChecked(false);
                    cb_java.setChecked(false);
                    cb_php.setChecked(false);
                    cb_c.setChecked(false);
                }
                break;
        }
    }
}

步骤三:查看效果图

Android基础控件——CheckBox多选框的全选功能_第1张图片


你可能感兴趣的:(android,checkbox,实战)