安卓开发教程13:滚动视图

184 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第13天,点击查看活动详情

在实际开发过程中我们经常需要对比较多的内容做滚动(滑动)显示的功能,一般有两种情况,水平滑动/垂直滑动,那么这时候就需要用到今天要给大家介绍的这两个组件ScrollView以及HorizontalScrollView。

需要注意的是,无论是ScrollView还是HorizontalScrollView,其内部只能放一个子元素,当然如果我们的内容比较多的话可以放在子元素内部包裹起来。类似结构:ScrollView > LinearLayout > n个 View。

一、水平滚动

在水平方向滚动的时候,它的layout_width属性一定要设置为warp_content。

示例:

创建三个水平方向宽高各200dp,背景色各不相同的View,使其可以水平滑动显示。

步骤如下:

  1. 建立一个HorizontalScrollView 标签,并设置宽度自适应,高度定义为200dp
  2. 建立一个LinearLayout 标签,设置为水平方向
  3. 建立多个个 View 标签,设置宽度为200dp

效果:

image.png

代码如下:

<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="200dp"
            android:layout_height="match_parent"
            android:background="@color/teal_200"
            />
        <View
            android:layout_width="200dp"
            android:layout_height="match_parent"
            android:background="@color/teal_700"
            />
        <View
            android:layout_width="200dp"
            android:layout_height="match_parent"
            android:background="@color/black"
            />

    </LinearLayout>
</HorizontalScrollView>

二、垂直滚动

在垂直方向滚动的时候,它的layout_height一定要设置为warp_content。

示例:

创建三个垂直方向高为400dp,背景色各不相同的View,使其可以垂直滑动显示。

步骤如下:

  1. 建立一个ScrollView 标签,并设置宽度继承父元素,高度根据内容自适应。
  2. 建立一个LinearLayout 标签,设置为垂直方向。
  3. 建立多个个 View 标签,设置高度为400dp

效果:

image.png

代码如下:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/black">

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

        <View
            android:layout_width="match_parent"
            android:layout_height="400dp"
            android:background="@color/purple_200"
            />

        <View
            android:layout_width="match_parent"
            android:layout_height="400dp"
            android:background="@color/purple_700"
            />

        <View
            android:layout_width="match_parent"
            android:layout_height="400dp"
            android:background="@color/black"
            />

    </LinearLayout>

</ScrollView>

注意

这里有一点需要注意,我们在Android Studio 中 xml 的编辑器中选择Split模式,视图是无法滚动的,想要看到可以滚动显示的效果必须在虚拟机中运行才可以。

那么这就是滚动视图的使用方法,虽然比较简单,但在我们以后的开发过程中它的使用频率会非常的高,几乎所有项目都或多或少的会用到它,大家一定要掌握这块的知识。