Android实现TextView 设置图片drawableLeft后内容居中

时间:2025-01-31 08:08:25

使用TextView 的drawableLeft或drawableRight设置文字左边放置图片或右边放置图片时。无法控制文字和图片的位置,如果想要实现文字和图片居中的效果就需要通过自定义TextView 来实现

主要实现思想是 重写onDraw方法,计算图片,文字,以及图文间隔的宽度。然后调用canvas的translate方法将整体在X轴方向平移

代码:

/**
 * Created by Answer on 2017/7/7.
 * <p>
 * 自定义Textview 实现 drawableLeft 居中的功能
 */

public class DrawableTextView extends TextView {
    public DrawableTextView(Context context) {
        super(context);
    }

    public DrawableTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public DrawableTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // getCompoundDrawables() : Returns drawables for the left, top, right, and bottom borders.
        Drawable[] drawable = getCompoundDrawables();
        //得到drawableLeft设置的drawable对象
        Drawable leftDrawable = drawable[0];
        if (leftDrawable != null) {
            //得到leftdrawable 的宽度
            int leftDrawableWidth = ();
            //得到drawable与text之间的间距
            int drawablePadding = getCompoundDrawablePadding();
            //得到文本的宽度
            int textWidth = (int) getPaint().measureText(getText().toString().trim());

            int bodyWidth = leftDrawableWidth + drawablePadding + textWidth;
            ();
            //将内容在X轴方向平移
            ((getWidth() - bodyWidth) / 2, 0);
        }

        (canvas);
    }
}


在xml中使用:

<
                android:
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_weight="1"
                android:background="@drawable/selector_item"
                android:drawableLeft="@mipmap/gif_like"
                android:drawablePadding="10dp"
                android:gravity="center_vertical"
                android:text="Like"
                android:textColor="#999999"
                android:textSize="12sp" />