Android CheckBox 复选框(drawable、style 自定义复选框)

4,005 阅读1分钟

一、正常使用

  • 代码

    <!-- CheckBox -->
    <CheckBox
        android:id="@+id/man"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="男"/>
    <!-- CheckBox -->
    <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();
            }
        }
    }
    
  • 效果

    temp.gif

二、drawable 自定义

  • Android drawable 与 mipmap 文件夹存放图片有区别

    box_check.png

    box_normal.png

  • xml 代码

    <!-- CheckBox -->
    <CheckBox
        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">
        <item
            android:state_enabled="true"
            android:state_checked="false"
            android:drawable="@drawable/box_normal"/>
        <item
            android:state_enabled="true"
            android:state_checked="true"
            android:drawable="@drawable/box_check"/>
    </selector>
    

    image.png

  • 效果

    temp.gif

二、style 自定义

  • 它还是基于 drawable 代码

  • xml 代码

    <!-- CheckBox -->
    <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">
            <!-- 导入 drawable 文件中的 check_box -->
            <item name="android:button">@drawable/check_box</item>
        </style>
    </resources>
    
  • 效果与 drawable 一致。