package cc.hent.www.ramo_cmedcial.CustomView; import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet; /**
* Created by he cs on 2018/1/2.
* drawable与text一起居中的textview
*/ public class DrawableTextView extends android.support.v7.widget.AppCompatTextView {
public DrawableTextView (Context context) {
this(context,null);
} public DrawableTextView (Context context, @Nullable AttributeSet attrs) {
this(context, attrs,-1);
} public DrawableTextView (Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
} @Override
protected void onDraw (Canvas canvas) { Drawable[] compoundDrawables = getCompoundDrawables();
if (compoundDrawables != null) {
Drawable left = compoundDrawables[0];
if (left != null) {
float textWidth = getPaint().measureText(getText().toString());
int compoundDrawablePadding = getCompoundDrawablePadding();
//获取drawable的宽度 Intrinsic 内在的
int leftWidth = left.getIntrinsicWidth(); float bodyWidth = textWidth+compoundDrawablePadding+leftWidth; canvas.translate((getWidth()-bodyWidth)/2,0);
}
} //一定要,后调用
super.onDraw(canvas);
} }
重点在于重写ondraw,其他属性同textview就可以,注意,在使用gravity的时候,center_vertical即可