用户登录
用户注册

分享至

Android的ScrollView

  • 作者: 活在当下123
  • 来源: 51数据库
  • 2021-07-08

昨天第一次遇到需要使用ScrollView的场景,总结一下。

一、简介

凡是这个界面的组成非常不规则,而且竖直方向长度不够就肯定需要使用Scrollview了。因为ListView处理的是规则的内容。至于带视差效果的滚动自然是ScrollView。

举个例子,比如一则新闻页,有配图,在配图下可以点击按钮了解更多,有标题,最后是全部的新闻内容。那么ListView显然不是最好的选择,但是一般的Layout,比如LinearLayout、RelativeLayout或者FrameLayout之类Layout也没法用。最后就只有ScrollView可以解决问题了。

补充:
ScrollView与listView

  1. ScrollView中不管多少的数据项,它都会全部给加载出来。ScrollView里面能摆放很多控件组件,高度超过ScrollView的高度的话就可以滚动了,ScrollView里面的东西是初始化完成了就存在了,就已经在内存中了。并且没有回收与复用,假设一个界面特别长,条目种类特别多,内存就会占用特别的大。当内存不足时就会导致内存溢出(OOM)。一般只有在渲染数据量少的情况下才会使用。
  2. ListView 是只显示自身listItem内的东西,比如你有30条,listview能显示20条。那开始内存里只有20条,当下滑时才加载后面的10条。一般适用于数据量多的list。

二、重点

ScrollView就是一种特殊的布局。当ScrollView的内容大于他本身的size的时候,ScrollView会自动添加滚动条,并可以竖直滑动。使用ScrollView有以下几点需要注意:

  1. ScrollView的直接子View只能有一个。也就是说如果你要使用很复杂的视图结构,必须把这些视图放在一个标准布局里,如LinearLayout、RelativeLayout等。
  2. 可以使用layout_width和layout_height给ScrollView指定大小。
  3. ScrollView只用来处理需要滚动的不规则视图的组合。大批量的列表数据展示可以使用ListView、GridView或者RecyclerView。
  4. ScrollView和ListView之类的嵌套使用时会有滑动冲突。不到不得已不要使用。
  5. ScrollView只支持竖直滑动,水平滑动使用HorizontalScrollView。
  6. ScrollView的android:fillViewport属性定义了是否可以拉伸其内容来填满viewport。你也可以调用方法setFillViewport(boolean)来达到一样的效果。
  7. ScrollView的android:scrollbars="none"属性定义了ScrollView滚动条的隐藏。你也可以在代码中获取ScrollView后进行scroll.setVerticalScrollBarEnabled(false)。

代码示例:

<?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>
软件
前端设计
程序设计
Java相关