滚动视图ScrollView

手机屏幕的显示空间有限,常常都需要上下滑动或者左右滑动才能看到其它页面的内容,但Android的节点布局不支持自行滚动。

这时需要借助SrcollView来实现。
其中竖直滑动的View为ScrollView,水平滚动的为HorizontalScrollView。虽然使用起来不复杂,但需要注意几点:
1、垂直滚动时,水平要设为wrap_content,竖直要设为wrap_content。
2、水平滚动与垂直滚动类似。
3、滚动视图ScrollView只能存在一个子视图,如存在多个视图,则会报错:Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <!--HorizontalScrollView为水平滚动视图,高度为200dp-->
<HorizontalScrollView
    android:layout_width="wrap_content"
    android:layout_height="200dp">
    <!--LinearLayout有两个视图,一个是蓝色,一个是黄色-->
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        >

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

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

    </LinearLayout>
</HorizontalScrollView>
<!--竖直方向滚动-->
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <!--其下两个View,一个绿色,一个橙色-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

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

        <View
            android:layout_width="wrap_content"
            android:layout_height="400dp"
            android:background="#ffffaa"/>
    </LinearLayout>
</ScrollView>

</LinearLayout>

有时ScrollView的实际内容不够,又想让他充满屏幕,如果把layout_heigt设置为match_parent,其仍然不会充满
正确的做法是:

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

fillViewport表示允许填满整个视图窗口。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值