设置工具类
public class ImageTextButton extends android.support.v7.widget.AppCompatTextView { private Drawable drawableLeft; private int scaleWidth; //dp值 private int scaleHeight; public ImageTextButton(Context context) { super(context); } public ImageTextButton(Context context, AttributeSet attrs) { super(context, attrs); init(context,attrs); } public ImageTextButton(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, UIUtils.dp2px(20)); scaleHeight = typedArray.getDimensionPixelOffset(R.styleable .ImageTextButton_drawableHeight, UIUtils.dp2px(20)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (drawableLeft != null) { drawableLeft.setBounds(0, 0, UIUtils.dp2px(scaleWidth), UIUtils.dp2px(scaleHeight)); } } @Override protected 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 = UIUtils.getContext().getResources().getDrawable(drawableLeftRes); invalidate(); } }
附上attrs:
<!-- 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中调用即可,让我们看一下效果
<com.guorentong.learn.organ.utils.ImageTextButton android:layout_width="match_parent" android:layout_height="wrap_content" android:drawablePadding="5dp" android:text="课程时长" android:textColor="@color/colorText" android:textSize="30px" app:drawableHeight="20px" app:drawableWidth="6px" app:leftDrawable="@drawable/lantiao" />