Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 為 TextView 與 EditText 加上捲軸:ScrollView 用法說明

編輯:Android 開發實例

TextView 與 EditText 分別是 Android 的文字顯示框與輸入框。受手機螢幕尺寸所限,當需要輸入大量文字或顯示較長內容時,單一螢幕往往容納不下,因此讓文字框具備捲動能力幾乎是必備的。本文說明如何加上捲軸。

做法其實很簡單:在文字控制項外層包一個 ScrollView 即可。以下以 TextView 為例做對照。

// A、未加捲動效果

<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@+id/textView"
/>
// B、加上捲動效果

<ScrollView
  android:id="@+id/scrollView"
  android:layout_width="fill_parent"
  android:layout_height="200px"
  android:background="@android:drawable/edit_text">

  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textView"
  />

</ScrollView>

由以上對比可以看出,只要在文字控制項外圍包上 ScrollView,就能讓文字框具備捲動能力。

幾個實務上必須知道的細節

1. 高度設定是關鍵。ScrollView 的 layout_height 必須是一個固定值(範例用 200px)或 match_parent,絕對不能設成 wrap_content——否則 ScrollView 會把內容全部撐開,捲軸永遠不會出現。這是最常見的失效原因。另外範例用 px 而非 dp,在多種螢幕密度下會有問題,建議改用 dp。

2. ScrollView 只能有一個直接子項。若要包多個控制項,需在外層加一個 LinearLayout 當作單一子元素。

3. EditText 有自己的捲動能力。多行輸入框其實不需要 ScrollView,只要設定:

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textMultiLine"
    android:maxLines="5"
    android:scrollbars="vertical"
    android:gravity="top|start" />

用 ScrollView 包住 EditText 反而會導致「捲不動內容、只能捲整個頁面」的衝突,因為兩者都想攔截垂直滑動手勢。這點在 Touch 事件分發的機制下是必然的結果。

4. 想要文字本身可捲動,也可用 MovementMethod。在程式碼中一行即可:

 textView.setMovementMethod(new ScrollingMovementMethod());

這種做法不必改版面結構,適合既有專案的小幅修改。

5. NestedScrollView 更靈活。若內容需要與 RecyclerView 等本身可捲動的控制項共存,用 androidx.core.widget.NestedScrollView 取代 ScrollView,它能正確處理巢狀捲動的協調。不過要注意效能:NestedScrollView 會一次性 inflate 與量測所有子項,內容很長時應改用 RecyclerView。

6. 別忘了加上捲動提示。可透過 android:scrollbarStyle 與 android:fadeScrollbars 調整捲軸外觀與是否自動淡出。

以上就是為文字框加上捲軸的完整做法與注意事項,希望對大家的 Android 開發有所幫助。

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