让TextView的drawableLeft与文本一起居中显示

 TextView的drawableLeft、drawableRight和drawableTop是一个常用、好用的属性,可以在文本的上下左右放置一个图片,而不使用更加复杂布局就能达到,我也常常喜欢用RadioButton的这几个属性实现很多效果,但是苦于不支持让drawbleLeft与文本一起居中,设置gravity为center也无济于事,终于有空研究了一下,这里与大家一起分享。

 

声明

 

欢迎转载,请注明出处!

 

博客园:http://www.cnblogs.com/

 

农民伯伯: http://www.cnblogs.com/over140/

 

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

 

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:drawableLeft="@drawable/pay_weixin"
        android:drawablePadding="10dp"
        android:textColor="@color/code08"
        android:textSize="16sp"
        android:text="微信支付" />

 

posted on 2015-12-10 14:48  大米稀饭  阅读(2838)  评论(0编辑  收藏  举报