一般是用来对齐Hint或text的位置,TextView设置了android:gravity为bottom或者top, 而drawleft默认为center且无属性值去改变。此时可以自定义TextView,重写ondraw方法:
/**
* drawableLeft置于bottom
*
*/
public class DrawableLeftBottomEditText extends EditText {
public DrawableLeftBottomEditText(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public DrawableLeftBottomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DrawableLeftBottomEditText(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable[] drawables = getCompoundDrawables();
if (drawables != null) {
Drawable drawableLeft = drawables[0];
if (drawableLeft != null && !TextUtils.isEmpty(getHint())) {
Rect r = drawableLeft.getBounds();
Rect rect = new Rect();
getPaint().getTextBounds(getHint().toString(), 0, 1, rect);/*Hint.length>=1*/
int ds = r.bottom - rect.bottom;
setGravity(Gravity.CENTER_VERTICAL);
canvas.translate(0, ds/2);
}
}
super.onDraw(canvas);
}
}
原理就是在绘制TextView时,获取drawable和Hint的高度差,然后设置gravity为center,再沿Y轴整体平移高度差个单位。