首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android TextView 文字過長自動判斷顯示頭尾:比較 TextView 與容器高度

     編輯:程式設計綜合問答

需求分析

多行 TextView 固定高度(如 110dp)。文字未超出時靠上顯示(gravity=top);超出時想顯示**尾部**內容(gravity=bottom),類似聊天氣泡最新訊息置底。

核心邏輯:測量後比較高度

<LinearLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="110dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:textSize="37sp" />
</LinearLayout>
TextView tv = findViewById(R.id.tv);
LinearLayout container = findViewById(R.id.container);

tv.setText(longText);

// 必須在 layout 完成後執行
container.post(() -> {
    if (tv.getHeight() > container.getHeight()) {
        tv.setGravity(Gravity.BOTTOM); // 文字超出,顯示尾部
    } else {
        tv.setGravity(Gravity.TOP);    // 未超出,顯示頭部
    }
});

關鍵點

  • TextView 高度設為 wrap_content,讓它自然撐開到實際文字高度。
  • 容器高度固定(或 match_parent 受限於父佈局)。
  • 用 View.post(Runnable) 或 ViewTreeObserver.OnGlobalLayoutListener 確保測量完成後再比較。
  • 若需動態文字變更,每次 setText 後都要重新比較。

進階:單行文字省略號

若為單行,直接用 XML 屬性:

<TextView
    android:singleLine="true"
    android:ellipsize="end"
    android:gravity="center_vertical" />

多行省略需 API 16+ android:maxLines + android:ellipsize,但無法自動切換頭尾顯示,需自訂 View 實現。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved