ScrollView絕對是各種教材、教程都或多或少遺漏的一個(gè)非常重要的視圖。凡是這個(gè)界面的組成非常不規(guī)則,而且豎直方向長度不夠就肯定需要使用Scrollview了。因?yàn)?code>ListView處理的是規(guī)則的內(nèi)容。至于帶視差效果的滾動自然是ScrollView的產(chǎn)物。本文會通過一個(gè)簡單的例子,講述如何使用Scrollview。
多數(shù)的Android應(yīng)用都會出現(xiàn)內(nèi)容尺寸超出屏幕的情況。比如一則新聞頁,有配圖,在配圖下可以點(diǎn)擊按鈕了解更多,有標(biāo)題,最后是全部的新聞內(nèi)容,假設(shè)這則內(nèi)容是勇士打敗騎士隊(duì)后詹姆斯又跑去哪里抱大腿的新聞。那么ListView顯然不是最好的選擇,但是一般的Layout,比如LinearLayout、RelativeLayout或者FrameLayout之類Layout也沒法用。最后就只有ScrollView可以解決問題了。
ScrollView就是這么一種特殊的布局。當(dāng)ScrollView的內(nèi)容大于他本身的size的時(shí)候,ScrollView會自動添加滾動條,并可以豎直滑動。
-
ScrollView的直接子View只能有一個(gè)。也就是說如果你要使用很復(fù)雜的視圖結(jié)構(gòu),就如上問中說的那條新聞,你必須把這些視圖放在一個(gè)標(biāo)準(zhǔn)布局里,如LinearLayout、RelativeLayout等。 - 你可以使用
layout_width和layout_height給ScrollView指定大小。 -
ScrollView只用來處理需要滾動的不規(guī)則視圖的組合。大批量的列表數(shù)據(jù)展示可以使用ListView、GridView或者RecyclerView。 -
ScrollView和ListView之類的嵌套使用時(shí)會有滑動沖突。不到不得已不要使用。 -
ScrollView只支持豎直滑動,水平滑動使用HorizontalScrollView。 -
ScrollView的android:fillViewport屬性定義了是否可以拉伸其內(nèi)容來填滿viewport。你可以可以調(diào)用方法setFillViewport(boolean)來達(dá)到一樣的效果。
Android的ScrollView示例

demo.png
布局
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context="demo.scrollviewdemo.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:scaleType="centerCrop"
android:src="@drawable/nba" />
<Button
android:id="@+id/knowMoreButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/know_more" />
<TextView
android:id="@+id/titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/title"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/contentTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/content"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</ScrollView>
原文地址:http://javatechig.com/android/android-scrollview-example