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

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

編輯:Android 開發實例

EditText 與 TextView 分別是 Android 的文字輸入框與文字顯示框。但受螢幕尺寸限制,當需要輸入大量文字或顯示長篇內容時,一個畫面根本裝不下。這時就要為它們加上捲軸。

做法:在外層包一個 ScrollView

其實非常簡單——只要在文字控制項外面包上 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:scrollbarStyle="outsideOverlay" android:background="@android:drawable/edit_text">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
    />
</ScrollView>

由此可見,只要在文字控制項外圍加上 ScrollView,就能讓文字框具備捲動能力。

兩個必學的實務重點

第一,高度必須固定。ScrollView 的 layout_height 要設成明確的數值(如上面的 200px),若寫成 fill_parent 或 wrap_content,捲動就不會發生——因為元件會直接把內容撐開而不啟動捲軸。

第二,ScrollView 只能有一個直接子節點。若內容包含多個元件,必須先包一層 LinearLayout 再放進去,否則會引發例外。另外要留意:ScrollView 不支援橫向捲動(橫向需用 HorizontalScrollView),也不適合包 ListView 這類本身可捲動的元件,兩層捲動同時運作會造成手勢衝突與效能問題。若想讓 EditText 本身可多行捲動,其實更簡潔的做法是設定 android:maxLines 與 android:scrollbars="vertical",不必額外包一層。

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