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

来源:互联网 发布:js在框架在打开 编辑:程序博客网 时间:2024/06/06 03:45

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


  

  1. /** 
  2.  * drawableLeft与文本一起居中显示 
  3.  *  
  4.  *  
  5.  */  
  6. public class DrawableCenterTextView extends TextView {  
  7.   
  8.     public DrawableCenterTextView(Context context, AttributeSet attrs,  
  9.             int defStyle) {  
  10.         super(context, attrs, defStyle);  
  11.     }  
  12.   
  13.     public DrawableCenterTextView(Context context, AttributeSet attrs) {  
  14.         super(context, attrs);  
  15.     }  
  16.   
  17.     public DrawableCenterTextView(Context context) {  
  18.         super(context);  
  19.     }  
  20.   
  21.     @Override  
  22.     protected void onDraw(Canvas canvas) {  
  23.         Drawable[] drawables = getCompoundDrawables();  
  24.         if (drawables != null) {  
  25.             Drawable drawableLeft = drawables[0];  
  26.             if (drawableLeft != null) {  
  27.                 float textWidth = getPaint().measureText(getText().toString());  
  28.                 int drawablePadding = getCompoundDrawablePadding();  
  29.                 int drawableWidth = 0;  
  30.                 drawableWidth = drawableLeft.getIntrinsicWidth();  
  31.                 float bodyWidth = textWidth + drawableWidth + drawablePadding;  
  32.                 canvas.translate((getWidth() - bodyWidth) / 20);  
  33.             }  
  34.         }  
  35.         super.onDraw(canvas);  
  36.     }  
  37. }  

0 0
原创粉丝点击