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

Android ScrollView 的兩種宣告方式

編輯:關於 Android 程式設計

Android 的版面配置一般來說有兩種宣告方式:一種寫在 XML 裡,另一種用程式碼動態建立。ScrollView 兩者都支援。

方式一:XML 宣告

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ScrollView
        android:id="@+id/Scroll"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
        <TextView
            android:id="@+id/txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

方式二:程式碼宣告

TextView txt = new TextView(this);
txt.setText(str);

ScrollView scrollView = new ScrollView(this);
scrollView.addView(txt);
setContentView(scrollView);

兩種方式效果相同,差別只在宣告位置。實務上除非版面完全靠程式動態組裝,否則 XML 宣告可讀性更好,也方便用 Preview 直接預覽。

使用 ScrollView 時有個務必牢記的限制:它只能包含一個直接子節點。如果你的內容有多個並排的元件,必須先包一層 LinearLayout 或其他 ViewGroup,再放進 ScrollView,否則執行時會直接拋出 IllegalStateException: ScrollView can host only one direct child。

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <!-- 這裡可以放多個子元件 -->
    </LinearLayout>
</ScrollView>

另外兩個常見細節:子容器的 layout_height 建議設為 wrap_content,設成 match_parent 會讓內容被壓縮而失去捲動效果;如果內容是 ListView 或 RecyclerView,不要嵌套在 ScrollView 裡——兩者都自己處理捲動手勢,嵌套會造成手勢衝突與嚴重的效能問題(ListView 會被強制完整 lay out,長列表直接卡住)。這種情況正確做法是使用 NestedScrollView 搭配 RecyclerView,或改用 RecyclerView 的多種 viewType 來實作。

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