类似的 EditText 也可以这样处理,同理其他方向的 drawable。新增了一些自定义属性可以方便的改变 drawable 的大小。
public class DrawableTextView extends TextView {
public static final int LEFT = 1, TOP = 2, RIGHT = 3, BOTTOM = 4;
public DrawableRightClickListener drawableRightClickListener;
public DrawableTextView(Context context) {
this(context, null);
}
public DrawableTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DrawableTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
public DrawableRightClickListener getDrawableRightClick() {
return drawableRightClickListener;
}
public void setDrawableRightClick(DrawableRightClickListener drawableRightClickListener) {
this.drawableRightClickListener = drawableRightClickListener;
}
//为了方便,直接写了一个内部类的接口
public interface DrawableRightClickListener {
void onDrawableRightClickListener(View view);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (drawableRightClickListener != null) {
Drawable rightDrawable = getCompoundDrawables()[2];
//判断的依据是获取点击区域相对于屏幕的x值比我(获取TextView的最右边界减去边界宽度)大就可以判断点击在Drawable上
if (rightDrawable != null && event.getRawX() >= (getRight() - rightDrawable.getBounds().width() - getPaddingRight())) {
drawableRightClickListener.onDrawableRightClickListener(this);
return true;
}
}
break;
}
return super.onTouchEvent(event);
}
private void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.DrawableTextView);
int mWidth = a
.getDimensionPixelSize(R.styleable.DrawableTextView_drawable_width, 0);
int mHeight = a.getDimensionPixelSize(R.styleable.DrawableTextView_drawable_height,
0);
Drawable mDrawable = a.getDrawable(R.styleable.DrawableTextView_drawable_src);
int mLocation = a.getInt(R.styleable.DrawableTextView_drawable_location, LEFT);
a.recycle();
drawDrawable(mDrawable, mWidth, mHeight, mLocation);
}
}
public void drawDrawable(Drawable mDrawable, int mWidth, int mHeight, int mLocation) {
if (mDrawable != null) {
if (mWidth != 0 && mHeight != 0) {
mDrawable.setBounds(0, 0, mWidth, mHeight);
}
switch (mLocation) {
case LEFT:
this.setCompoundDrawables(mDrawable, null,
null, null);
break;
case TOP:
this.setCompoundDrawables(null, mDrawable,
null, null);
break;
case RIGHT:
this.setCompoundDrawables(null, null,
mDrawable, null);
break;
case BOTTOM:
this.setCompoundDrawables(null, null, null,
mDrawable);
break;
}
}
}
}
//对应的自定义属性
<!--DrawableTextView-->
<declare-styleable name="DrawableTextView">
<attr name="drawable_src" format="reference"/>
<attr name="drawable_height" format="dimension"/>
<attr name="drawable_width" format="dimension"/>
<attr name="drawable_location">
<enum name="left" value="1"/>
<enum name="top" value="2"/>
<enum name="right" value="3"/>
<enum name="bottom" value="4"/>
</attr>
</declare-styleable>