android:id
=
"@+id/man"
android:layout_width
=
"wrap_content"
android:layout_height
=
"wrap_content"
android:text
=
"男"
/>
<
CheckBox
android:id
=
"@+id/woman"
android:layout_width
=
"wrap_content"
android:layout_height
=
"wrap_content"
android:text
=
"女"
/>
如果需要
设置文字与选择框的距离
,加上
android:paddingLeft="5dp"
配置即可。
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
@SuppressLint("WrongConstant")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckBox manBox = (CheckBox) findViewById(R.id.man);
CheckBox womanBox = (CheckBox) findViewById(R.id.woman);
manBox.setOnCheckedChangeListener(this);
womanBox.setOnCheckedChangeListener(this);
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String str = compoundButton.getText().toString();
if (compoundButton.isChecked()) {
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
二、drawable 自定义
Android drawable 与 mipmap 文件夹存放图片有区别
android:id="@+id/none"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="无"
android:button="@drawable/check_box"/>
drawable 代码
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
android:state_enabled="true"
android:state_checked="false"
android:drawable="@drawable/box_normal"/>
android:state_enabled="true"
android:state_checked="true"
android:drawable="@drawable/box_check"/>
</selector>
二、style 自定义
它还是基于 drawable 代码
xml 代码
<CheckBox
android:id="@+id/none"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/MyCheckBox"
android:text="无"/>
drawable 代码,需要在 res/values/styles.xml 文件中添加,如果没有 styles.xml 手动创建一下。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyCheckBox">
<item name="android:button">@drawable/check_box</item>
</style>
</resources>
效果与 drawable 一致。