滚动视图ScrollView

2018-01-09 11:24:16

滚动视图ScrollView

手机屏幕的显示空间有限,常常需要上下滑动或左右滑动才能拉出其余页面内容,可惜Android的布局节点都不支持自行滚动,这时就要借助ScrollView滚动视图实现了。与线性布局类似,滚动视图也分为垂直方向和水平方向两类,其中垂直滚动的视图名是ScrollView,水平滚动的视图名为HorizontalScrollView。这两个滚动视图的使用并不复杂,主要注意以下3点.

  • 垂直方向滚动时,layout_width要设置为match_parent,layout_height要设置为wrap_content
  • 水平方向滚动时,layout_width要设置为wrap_content,layout_height要设置为match_parent
  • 滚动视图节点下面必须且只能挂着一个子布局节点,否则会在运行时报错Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child.
    下面是滚动视图ScrollView和水平滚动视图HorizontalScrollView的XML的用法示例:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="200dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <View
                android:layout_width="400dp"
                android:layout_height="match_parent"
                android:background="#ffff00" />

            <View
                android:layout_width="400dp"
                android:layout_height="match_parent"
                android:background="#aaffff" />

        </LinearLayout>

    </HorizontalScrollView>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            >

            <View
                android:layout_width="match_parent"
                android:layout_height="400dp"
                android:background="#00ff00" />

            <View
                android:layout_width="match_parent"
                android:layout_height="400dp"
                android:background="#ffffaa" />

        </LinearLayout>

    </ScrollView>

</LinearLayout>

有时ScrollView的实际内容不够,又不想让它充满屏幕,怎么办呢?如果把layout_height属性赋值为match_parent,那么结果还是不会充满,正确的做法是再增加一行fillViewport性性设置,举例如下:

android: layout_height="match_parent"
android: fillViewport="true"