Android基础控件CheckBox的使用
作者:互联网
CheckBox有两种状态,勾选和未勾选,是一个很简单的控件。可以通过实现OnCheckedChangeListener接口来监听CheckBox;如果想更改它的图标的话只需更改它的Button属性即可实现。下面是示例代码。
- check_box_selector.xml
<?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>
- check_box_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CheckBoxActivity"
android:orientation="vertical">
<!--系统自带图标的CheckBox-->
<CheckBox
android:id="@+id/ck_check_box_demo1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:text="这是一个系统自带图标的CheckBox"
android:textSize="18sp"/>
<!--自定义图标的CheckBox-->
<CheckBox
android:id="@+id/ck_check_box_demo2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:text="这是一个改了图标的CheckBox"
android:textSize="18sp"
android:button="@drawable/check_box_selector"/>
</LinearLayout>
- CheckBoxActivity.java
package xyz.strasae.androidlearn.my;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
public class CheckBoxActivity extends AppCompatActivity {
CheckBox checkBoxDemo1;
CheckBox checkBoxDemo2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_box);
checkBoxDemo1 = findViewById(R.id.ck_check_box_demo1);
checkBoxDemo1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
Toast.makeText(CheckBoxActivity.this, String.format("你碰了了控件%s,状态为%b", compoundButton.getText().toString(), b), Toast.LENGTH_SHORT).show();
}
});
checkBoxDemo2 = findViewById(R.id.ck_check_box_demo2);
checkBoxDemo2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
Toast.makeText(CheckBoxActivity.this, String.format("你碰了了控件%s,状态为%b", compoundButton.getText().toString(), b), Toast.LENGTH_SHORT).show();
}
});
}
}
标签:Toast,控件,CheckBox,box,check,import,Android,CompoundButton 来源: https://blog.csdn.net/weixin_43219615/article/details/98856966