首页 > 系统 > Android > 正文

Android TextView的drawLeft无法与文字一起居中解决方案

2019-11-08 00:09:55
字体:
来源:转载
供稿:网友

    TextView的drawableLeft、drawableRight和drawableTop不支持让drawbleLeft与文本一起居中,设置gravity为center也无济于事,重写一下TextView即可解决。

  

/**  * drawableLeft与文本一起居中显示  *   *   */  public class DrawableCenterTextView extends TextView {        public DrawableCenterTextView(Context context, AttributeSet attrs,              int defStyle) {          super(context, attrs, defStyle);      }        public DrawableCenterTextView(Context context, AttributeSet attrs) {          super(context, attrs);      }        public DrawableCenterTextView(Context context) {          super(context);      }        @Override      PRotected void onDraw(Canvas canvas) {          Drawable[] drawables = getCompoundDrawables();          if (drawables != null) {              Drawable drawableLeft = drawables[0];              if (drawableLeft != null) {                  float textWidth = getPaint().measureText(getText().toString());                  int drawablePadding = getCompoundDrawablePadding();                  int drawableWidth = 0;                  drawableWidth = drawableLeft.getIntrinsicWidth();                  float bodyWidth = textWidth + drawableWidth + drawablePadding;                  canvas.translate((getWidth() - bodyWidth) / 2, 0);              }          }          super.onDraw(canvas);      }  }  


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表