Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義 TextView 讓 drawableLeft 與文字整體居中

編輯:關於 Android 程式設計

使用 TextView 的 drawableLeft 屬性時,圖示會貼齊文字左側,導致「圖片+文字」整體偏左,視覺上不居中。要解決這個問題,最簡單的辦法是自定義一個 TextView,在繪製前對畫布做水平位移。

一、自定義控制元件

package com.test.signcalendar.weight;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 自定義 TextView,讓 drawableLeft 能與文字一起居中
 */
public class DrawableCenterTextView extends TextView {
    public DrawableCenterTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    public DrawableCenterTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public DrawableCenterTextView(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable[] drawables = getCompoundDrawables();
        if (drawables != null) {
            Drawable drawableLeft = drawables[0];
            if (drawableLeft != null) {
                float textWidth = getPaint().measureText(getText().toString());
                int drawablePadding = getCompoundDrawablePadding();
                int drawableWidth = drawableLeft.getIntrinsicWidth();
                float bodyWidth = textWidth + drawableWidth + drawablePadding;
                // 整體內容寬度 = 文字 + 圖示 + 間距,算出偏移量後平移畫布
                canvas.translate((getWidth() - bodyWidth) / 2, 0);
            }
        }
        super.onDraw(canvas);
    }
}

原理很單純:先用 measureText 量出文字寬度,加上圖示固有寬度與 drawablePadding,得到內容總寬,再用剩餘空間的一半去平移畫布,圖文作為一個整體就居中了。

二、在版面檔中引用

<com.test.signcalendar.weight.DrawableCenterTextView
    android:id="@+id/textView1111"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:drawableLeft="@drawable/fmhp_mine_health_plan_signcalendar_finish_status_bg"
    android:drawablePadding="5dp"
    android:text="都完成"
    android:textColor="#333333"
    android:textSize="12sp" />

三、效果

這樣就達到了圖文整體居中的效果。若同時需要 drawableRight,只要把右側圖示也納入 bodyWidth 的計算即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved