手机屏幕的显示空间有限,常常都需要上下滑动或者左右滑动才能看到其它页面的内容,但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表示允许填满整个视图窗口。