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

Android TextView 加上垂直捲軸:外面包一層 ScrollView 就搞定

編輯:關於 Android 程式設計

要在畫面上顯示一段長文字,又不想讓它撐破版面,最簡單的辦法是用 ScrollView 把 TextView 包起來。比起在 TextView 上想辦法開啟捲動,這種寫法的效果通常更可控。

<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:fadingEdge="vertical"
    android:scrollbars="vertical" >

    <TextView
        android:id="@+id/ee_source"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dip"
        android:text="AAAA"
        android:textColor="#8F683A"
        android:textSize="18dip" />

</ScrollView>

幾個屬性的作用

android:scrollbars="vertical" 決定捲軸方向;android:fadingEdge="vertical" 讓上下邊緣在捲動時出現漸層淡出效果,視覺上暗示「還有更多內容」,比突兀的切邊舒服得多。

最關鍵的其實是 ScrollView 自己那個固定的 layout_height="150dp"。捲動之所以會發生,是因為「視窗高度」小於「內容高度」。如果你讓 ScrollView 用 match_parent、內容又不夠長,那它根本不會捲。反過來,包在裡面的 TextView 應該用 wrap_content,讓它能依文字長度自由長高。

兩個限制要記住

ScrollView 只能有一個直接子元素,多放一個就會在執行時報錯,需要多欄時請再包一層 LinearLayout。另外它是垂直專用,水平捲動得換成 HorizontalScrollView。

如果不想動到版面結構,TextView 其實也有內建方案:tv.setMovementMethod(ScrollingMovementMethod.getInstance()); 就能讓文字本身可捲動。這招在「一個畫面裡有多塊文字各自需要獨立捲動」時特別好用,因為不必嵌套好幾層 ScrollView。至於整頁的長文,則該直接讓 ScrollView 包住整個內容區,而不是只包其中一段。

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