android动态添加checkbox及样式(替换默认图片)
2017-12-04 21:27
603 查看
日常开发中,常常会碰到自定义控件动态添加checkbox的情况,添加比较简单,就不多说了,这里我要说的是如何替换默认选中图片效果以及其样式。
代码如下:
1、在drawable文件新建cb_common.xml文件
2、控件中创建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) { } });
相关文章推荐
- checkbox、radio样式(用图片换掉默认样式)
- [Android] 通过GridView仿微信动态添加本地图片
- [Android] 通过GridView仿微信动态添加本地图片
- android checkbox 未选中状态 已选中状态 替换成自己的图片
- 仿QQ发布图片动态-添加图片-GridView浏览图片-CheckBox设置已经选中的图片
- Android 代码中动态添加图片使图片缩放并保持宽高比
- 【android开发】CheckBox加载自定义选中与未选中图片样式
- [Android] 通过GridView仿微信动态添加本地图片示例代码
- Android绘图实例(Bitmmap,Canvas,Pain的使用)&动态的在图片上添加文字(canvas.drawText)
- android 动态添加的checkbox设置间距大小
- android 动态向Gallery中添加图片及倒影&&3D效果
- checkbox用图片替换原始样式,并实现同样的功能
- android替换默认壁纸并添加壁纸进壁纸库
- Android 为CheckBoxPreference Preference 控件添加样式
- android动态添加控件并设置位置样式
- 关于android 动态设置view 样式 问题(默认style)
- Android GridView扩展仿微信微博发图动态添加删除图片
- android 动态向Gallery中添加图片及倒影&&3D效果
- Android系统默认对话框添加图片功能
- android 下改变默认的checkbox的 选中 和被选中 图片