CheckBox 的基本用法
设置复选框的Check状态的时候,调用 setChecked() 方法。
追加 Android 复选框被选择时处理的时候,调用 setOnCheckedChangeListener() 方法,
并把 CompoundButton.OnCheckedChangeListener 实例作为参数传入
在 CompoundButton.OnCheckedChangeListener 的 onCheckedChanged() 方法里,取得被选中 Android 复选框的实例。
一个小例子展示最基本的用法。
在 activity_xml 中引入一个 CheckBox 控件。
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center">
<CheckBox
android:id="@+id/test_cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"/>
</LinearLayout>
java 类中可以这样用:
package com.example.a002034.checkboxdemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
public class MainActivity extends Activity {
private CheckBox mCheckBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCheckBox = findViewById(R.id.test_cb);
mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Toast.makeText(MainActivity.this,buttonView.getText().toString(),Toast.LENGTH_SHORT)
.show();
}
}
});
}
}
自定义 CheckBox 样式
1.首先在drawable文件夹中添加drawable文件checkbox_style.xml。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/checkbox_pressed" android:state_checked="true"/>
<item android:drawable="@drawable/checkbox_normal" android:state_checked="false"/>
<item android:drawable="@drawable/checkbox_normal"/>
</selector>
2.在values文件夹下的styles.xml文件中添加CustomCheckboxTheme样式。
<style name="CustomCheckboxTheme" parent="@android:style/Widget.CompoundButton.CheckBox">
<item name="android:button">@drawable/checkbox_style</item>
</style>
3.在布局文件中使用CustomCheckboxTheme样式。
<CheckBox
android:id="@+id/select_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/CustomCheckboxTheme" />
使用到的图片资源
checkbox_normal.png
checkbox_pressed.png