使用有自定义图标的CheckBox:
Button按钮的背景在正常情况下是凸起的,在按下时是凹陷的,从按下到弹起的过程,用户便能知道点击了这个按钮。
在项目中创建状态图形的XML文件,则需右击drawable目录,然后在右键菜单中依次选择New→Drawable resource file,即可自动生成一个空的XML文件。
下面是一个状态列表图形的drawable文件:
===================================================================================
xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/check_choose"/>
<item android:drawable="@drawable/check_unchoose"/>
selector>
<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="5dp" >
<CheckBox
android:id="@+id/ck_system"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:checked="false"
android:text="这是系统的CheckBox"
android:textColor="@color/black"
android:textSize="17sp" />
<CheckBox
android:id="@+id/ck_custom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:button="@drawable/checkbox_selector"
android:padding="5dp"
android:checked="false"
android:text="这个CheckBox换了图标"
android:textColor="@color/black"
android:textSize="17sp" />
LinearLayout>
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("DefaultLocale")
// 该页面实现了接口OnCheckedChangeListener,意味着要重写勾选监听器的onCheckedChanged方法
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 从布局文件中获取名叫ck_system的复选框
CheckBox ck_system = findViewById(R.id.ck_system);
// 从布局文件中获取名叫ck_custom的复选框
CheckBox ck_custom = findViewById(R.id.ck_custom);
// 给ck_system设置勾选监听器,一旦用户点击复选框,就触发监听器的onCheckedChanged方法
ck_system.setOnCheckedChangeListener(this);
// 给ck_custom设置勾选监听器,一旦用户点击复选框,就触发监听器的onCheckedChanged方法
ck_custom.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
String desc = String.format("您%s了这个CheckBox", isChecked ? "勾选" : "取消勾选");
buttonView.setText(desc);
}
}