实现界面:
复选框经典用法、自定义复选框按钮、设置复选框监听
常用属性:
android:text 设置选项文本
android:button 自定义复选框按钮
android:textSize 设置文本字体大小
android:checked="true" 设置默认选中
android:textColor 设置文本颜色
android:textSize 设置文本大小
代码实现:
activity_check_box.xml:布局文件
CheckBoxActivity:java文件
package com.example.administrator.exercise;import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;public class CheckBoxActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener{private CheckBox checkBox,checkBox1,checkBox2,checkBox3,checkBox4,checkBox5,checkBox6,checkBox7;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_check_box);checkBox = (CheckBox) findViewById(R.id.cb_1);checkBox.setOnCheckedChangeListener(this);checkBox1 = (CheckBox) findViewById(R.id.cb_2);checkBox1.setOnCheckedChangeListener(this);checkBox2 = (CheckBox) findViewById(R.id.cb_3);checkBox2.setOnCheckedChangeListener(this);checkBox3 = (CheckBox) findViewById(R.id.cb_4);checkBox3.setOnCheckedChangeListener(this);checkBox4 = (CheckBox) findViewById(R.id.cb_5);checkBox4.setOnCheckedChangeListener(this);checkBox5 = (CheckBox) findViewById(R.id.cb_6);checkBox5.setOnCheckedChangeListener(this);checkBox6 = (CheckBox) findViewById(R.id.cb_7);checkBox6.setOnCheckedChangeListener(this);checkBox7 = (CheckBox) findViewById(R.id.cb_8);checkBox7.setOnCheckedChangeListener(this);}//监听器的参数//第一个参数:被点击的按钮//第二个参数:是否选中@Overridepublic void onCheckedChanged(CompoundButton compoundButton, boolean b) {Toast.makeText(CheckBoxActivity.this,b?compoundButton.getText():"未选中",Toast.LENGTH_SHORT).show();}
}
selector_orange_checkbox.xml:自定义背景文件
选中时选取背景1,未选中时选取背景2