Android DrawableTextView图片文字居中显示。在我们开发中,TextView设置android:drawableLeft一定使用的非常多,但Drawable和Text同时居中显示可能不好控制,有没有好的办法解决呢?

我的方案是通过自定义TextView实现。

实现的效果图:

Android DrawableTextView图片文字居中显示

注:第一行为原生TextView添加android:drawableLeft

第二行为自定义TextView实现的效果。

实现思路:

继承TextView,覆盖onDraw(Canvas canvas),在onDraw中先将canvas进行translate平移,再调用父类onDraw进行绘制。

 1 package com.xing.drawabletextview;
 2  
 3 import android.content.Context;
 4  
 5 import android.graphics.Canvas;
 6  
 7 import android.graphics.drawable.Drawable;
 8  
 9 import android.util.AttributeSet;
10  
11 import android.widget.TextView;
12  
13 /**
14  
15 * Created by Administrator on 2017/2/28.
16  
17 */
18  
19 public class DrawableTextView extends TextView {
20  
21 public DrawableTextView(Context context) {
22  
23 this(context, null);
24  
25 }
26  
27 public DrawableTextView(Context context, AttributeSet attrs) {
28  
29 this(context, attrs, 0);
30  
31 }
32  
33 public DrawableTextView(Context context, AttributeSet attrs, int defStyleAttr) {
34  
35 super(context, attrs, defStyleAttr);
36  
37 }
38  
39 @Override
40  
41 protected void onDraw(Canvas canvas) {
42  
43 // getCompoundDrawables() : Returns drawables for the left, top, right, and bottom borders.
44  
45 Drawable[] drawables = getCompoundDrawables();
46  
47 // 得到drawableLeft设置的drawable对象
48  
49 Drawable leftDrawable = drawables[0];
50  
51 if (leftDrawable != null) {
52  
53 // 得到leftDrawable的宽度
54  
55 int leftDrawableWidth = leftDrawable.getIntrinsicWidth();
56  
57 // 得到drawable与text之间的间距
58  
59 int drawablePadding = getCompoundDrawablePadding();
60  
61 // 得到文本的宽度
62  
63 int textWidth = (int) getPaint().measureText(getText().toString().trim());
64  
65 int bodyWidth = leftDrawableWidth + drawablePadding + textWidth;
66  
67 canvas.save();
68  
69 canvas.translate((getWidth() - bodyWidth) / 2, 0);
70  
71 }
72  
73 super.onDraw(canvas);
74  
75 }
76  
77 }
DrawableTextView

相关文章: