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

自訂 CenterTextView:讓 Android 的換行文字優雅置中

編輯:關於 Android 程式設計

做 App 時 TextView 大概是使用頻率最高的控制項,功能也確實強大。但它仍有幾個邊角處不太順手,最典型的例子就是換行對齊。當一段字串超過螢幕寬度時,系統會自動換行,然而預設的換行效果是「頂齊」,也就是每一行都從最左側開始,視覺上參差不齊。設計稿要求的卻往往是換行後整體置中——這件事在 iOS 上垂手可得,在 Android 就得自己動手做一個 View。

先看最終效果:

從原始碼裡找線索

翻 android.text 包的時候,注意到幾個平常幾乎不會碰到的類別:Layout、StaticLayout、DynamicLayout。查了資料才理解它們的角色——這 trio 正是負責對 CharSequence 及其子類做排版的核心,只要傳入不同的 Alignment,它們就會依該對齊方式處理文字。

既然如此,思路就很清楚了:覆寫 TextView 的 onDraw,把畫面的主導權交給 StaticLayout,並將對齊方式指定為 ALIGN_CENTER。

CenterTextView 實作

public class CenterTextView extends TextView {

    private StaticLayout myStaticLayout;
    private TextPaint tp;

    public CenterTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        initView();
    }

    private void initView() {
        tp = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        tp.setTextSize(getTextSize());
        tp.setColor(getCurrentTextColor());
        // 關鍵在這裡:對齊方式改為 ALIGN_CENTER
        myStaticLayout = new StaticLayout(getText(), tp, getWidth(),
                Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        myStaticLayout.draw(canvas);
    }
}

在配置檔中使用

用法與一般的 TextView 幾乎相同,只是要把標籤換成自訂 View 的完整類別名稱:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="最美的不是下雨天,是和你一起躲過雨的屋檐,美麗的畫面。" />

    <com.example.materialdesigndemo.CenterTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/text"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="最美的不是下雨天,是和你一起躲過雨的屋檐,美麗的畫面。" />
</RelativeLayout>

這個做法的取捨

整個改動只集中在一個 onDraw 方法上,成本極低,但代價也相當明確:因為畫面完全交由 StaticLayout 一手包辦,CenterTextView 就只認得文字,沒辦法再顯示 drawableLeft、drawableRight 這類複合圖示。若需求裡真的有圖示要一起排,就必須在 onDraw 中自行計算圖示的繪製位置並呼叫 canvas 相關方法,複雜度會上升一截。

另一個實務上的小陷阱是:StaticLayout 是在 onSizeChanged 時機以當下的 getWidth() 建構的,若你的 TextView 寬度會隨 LayoutParams 或字級設定變動,記得在對應的回呼裡重新呼叫一次 initView,否則排版會與實際寬度脫節。

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