文章目录
- 概要
- 自定义CheckBoX
- 资源文件如下
- 使用方法
- 实现效果
概要
目前要实现类似于Radiobutton选择按钮,如果只有一个RadioButton,就不能和radio Group连用,导致选择没办法取消,如果要实现只能代码中进行操作,过于繁琐。所以自己写了一个定义CheckBox样式,实现的效果和RadioBUtton样式一样,不过能够实现选择和取消,代码中直接实现监听即可,这样就方便使用了
自定义CheckBoX
具体实现代码如下:
public class CheckButton extends CheckBox {private Drawable drawableLeft;private int scaleWidth; //dp值private int scaleHeight;public CheckButton(Context context) {super(context);}public CheckButton(Context context, AttributeSet attrs) {super(context, attrs);init(context,attrs);}public CheckButton(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);init(context, attrs);}public void init(Context context, AttributeSet attrs) {TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageTextButton);drawableLeft = typedArray.getDrawable(R.styleable.ImageTextButton_leftDrawable);scaleWidth = typedArray.getDimensionPixelOffset(R.styleable.ImageTextButton_drawableWidth, 20);scaleHeight = typedArray.getDimensionPixelOffset(R.styleable.ImageTextButton_drawableHeight, 20);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);if (drawableLeft != null) {drawableLeft.setBounds(0, 0,scaleWidth, scaleHeight);}}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);this.setCompoundDrawables(drawableLeft, null, null, null);}/*** 设置左侧图片并重绘* @param drawableLeft*/public void setDrawableLeft(Drawable drawableLeft) {this.drawableLeft = drawableLeft;invalidate();}/*** 设置左侧图片并重绘* @param drawableLeftRes*/public void setDrawableLeft(int drawableLeftRes) {this.drawableLeft = getContext().getResources().getDrawable(drawableLeftRes);invalidate();}
}
资源文件如下
放在res目录下的styles中
<!-- ImageTextButton attrs--><attr name="leftDrawable" format="reference"/><attr name="drawableWidth" format="dimension"/><attr name="drawableHeight" format="dimension"/><declare-styleable name="ImageTextButton"><attr name="leftDrawable"/><attr name="drawableWidth"/><attr name="drawableHeight"/></declare-styleable>
使用方法
直接在xml布局中引用CheckButton即可,代码如下
<com.CheckButtonandroid:id="@+id/tz_checkbox1"android:layout_width="match_parent"android:layout_height="wrap_content"android:textSize="15sp"android:drawablePadding="5dp"app:drawableWidth="20dp"app:drawableHeight="20dp"android:button="@null"android:text="我是自定义CheckBox"app:leftDrawable="@drawable/radion_select"/>
实现效果
写到这里就大功告成!!!