您的位置:首页 > 移动开发 > Android开发

android动态添加checkbox及样式(替换默认图片)

2017-12-04 21:27 549 查看
日常开发中,常常会碰到自定义控件动态添加checkbox的情况,添加比较简单,就不多说了,这里我要说的是如何替换默认选中图片效果以及其样式。

代码如下:

1、在drawable文件新建cb_common.xml文件

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/checked" android:state_enabled="false" android:state_checked="true"/>
<item android:drawable="@drawable/transparent" android:state_enabled="false" android:state_checked="false"/>
<item android:drawable="@drawable/cb_checked" android:state_checked="true"/>
<item android:drawable="@drawable/cb_unchecked" android:state_checked="false"/>

</selector>


2、控件中创建checkbox及引用

CheckBox checkBox = new CheckBox(getContext());
checkBox.setText(value);
checkBox.setTextColor(Color.BLACK);
checkBox.setTextSize(20);
checkBox.setPadding(20, 7, 0, 7);
//设置一张透明图片
checkBox.setButtonDrawable(R.drawable.transparent);

Drawable cbCommon;
Resources res = getResources();
//把自定义的样式图片写入cb_common文件中
cbCommon = res.getDrawable(R.drawable.cb_common);
//这里要注意,该方法是绘制文字前面的图片,图片宽度等同于文字宽度,即图片宽度+文字宽度=总内容宽度,
//所以设置样式的时候注意缩进,且该方法不可缺少
cbCommon.setBounds(0, 0, cbCommon.getMinimumWidth(), cbCommon.getMinimumHeight());
checkBox.setCompoundDrawables(cbCommon, null, null, null); //设置左图标
checkBox.setCompoundDrawablePadding(5);

checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息