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

Android ListView Item 佈局異常:文字過長撐大、時間不顯示的根因與修復

     編輯:程式設計疑難解答

典型錯誤佈局

<LinearLayout xmlns:android="..."
    android:layout_width="match_parent"
    android:layout_height="match_parent">  <!-- 錯誤:match_parent -->
    <TextView android:id="@+id/tv_content" ... />
    <TextView android:id="@+id/tv_time" ... />
</LinearLayout>

現象

  • 內容過長時 Item 高度異常增大,佈局撐爆。
  • 時間 TextView 被擠壓不顯示或換行錯亂。

根因

layout_height="match_parent" 讓 Item 在 ListView 測量階段獲得「盡可能大」的高度建議,配合 wrap_content 的子 View 導致測量傳遞混亂,最終由最長文本決定整體高度。

修復方案

<LinearLayout ...
    android:layout_width="match_parent"
    android:layout_height="wrap_content">  <!-- 正確:wrap_content -->
    <TextView
        android:id="@+id/tv_content"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:maxLines="2"
        android:ellipsize="end" />
    <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp" />
</LinearLayout>

關鍵點

  1. 根佈局高度必須 wrap_content,讓 Item 高度由內容決定。
  2. 長文本 TextView 設置 maxLines + ellipsize="end" 防止無限撐高。
  3. 使用 layout_weight 分配寬度,保證時間區域不被擠壓。
  4. 若需固定高度,用具體 dp 值而非 match_parent。

進階:RecyclerView 同理

ViewHolder 的根 itemView 在 onCreateViewHolder 中 inflate 時,父容器傳 null 或 parent, false,根佈局高度同樣應為 wrap_content。

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