在複雜佈局中,僅需讓特定 TextView 垂直滾動,而非整個頁面滾動。直接在 LinearLayout/RelativeLayout 中設置 android:scrollbars="vertical" 無效,必須用 ScrollView 包裹目標 TextView。
<RelativeLayout
android:layout_width="250dp"
android:layout_height="374dp"
android:layout_marginBottom="6dp"
android:layout_marginLeft="35dp"
android:layout_marginTop="20dp"
android:background="#C71585">
<!-- 上部固定內容 -->
<RelativeLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="25dp"
android:background="@drawable/add_schedule_bg">
<!-- 按鈕區域 -->
</RelativeLayout>
<ImageView
android:id="@+id/breakARTISTIMAGE"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_below="@id/linearLayout1"
android:layout_marginTop="14dp"
android:src="@drawable/ic_launcher"/>
<!-- 關鍵:ScrollView 包裹需滾動的 TextView -->
<ScrollView
android:id="@+id/breakSCROLLVIEW"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@id/breakARTISTIMAGE"
android:layout_above="@id/breakARTISTIMAGE2">
<TextView
android:id="@+id/breakARTISTDESCRIPTION"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"/>
</ScrollView>
<ImageView
android:id="@+id/breakARTISTIMAGE2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentRight="true"
android:layout_above="@id/breakSCROLLVIEW"
android:src="@drawable/ic_launcher"/>
</RelativeLayout>
| 屬性 | 作用 | 注意事項 |
|---|---|---|
android:layout_height="wrap_content" | ScrollView 高度自適應內容 | 需配合上下約束限制最大高度 |
android:layout_above="@id/breakARTISTIMAGE2" | 底部留空給固定圖片 | 避免內容被底部元素遮擋 |
android:fillViewport="true" | 內容不足時撐滿可視區 | 可選,視設計需求 |
android:scrollbars="vertical" | 顯示垂直滾動條 | API 23+ 需 android:scrollbarThumbVertical |
textView.post(() -> {
int lineCount = textView.getLineCount();
if (lineCount > MAX_VISIBLE_LINES) {
scrollView.setVerticalScrollBarEnabled(true);
} else {
scrollView.setVerticalScrollBarEnabled(false);
}
});
// 父佈局為 RecyclerView/NestedScrollView 時
scrollView.setNestedScrollingEnabled(true);
// 子 TextView 禁止攔截觸摸事件
textView.setOnTouchListener((v, event) -> {
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
});
// 超過 5000 字符建議分頁
public class PagedTextView extends TextView {
private static final int PAGE_SIZE = 3000;
private List pages = new ArrayList<>();
private int currentPage = 0;
public void setFullText(String text) {
// 智能分頁邏輯(保留段落完整性)
splitIntoPages(text);
showPage(0);
}
}
NestedScrollViewlayout_height="match_parent" 導致 ScrollView 無法滾動:必須用 wrap_content + 約束android:singleLine="true" 會禁用換行滾動setLayerType(LAYER_TYPE_SOFTWARE, null)