• 让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="微信支付" />
  • 相关阅读:
    WEB前端开发规范文档
    js九九乘法表
    阿里前端两年随想
    自动播放选项卡
    HTML+CSS编写规范
    简易秒表
    关于响应式布局
    关于PHP语言
    关于CSS3的小知识点之2D变换
    关于H5框架之Bootstrap的小知识
  • 原文地址:https://www.cnblogs.com/androidsj/p/5036022.html
Copyright © 2020-2023  润新知