滚动视图ScrollView

手机屏幕的显示空间有限,常常需要上下滑动或左右滑动才能拉出其余页面内容,可惜一般的布局节点
都不支持自行滚动,这时就要借助滚动视图了。与线性布局类似,滚动视图也分为垂直方向和水平方向
两类,其中垂直滚动视图名为ScrollView,水平滚动视图名为HorizontalScrollView。这两个滚动视图的
使用并不复杂,主要注意以下3点: 
(1)垂直方向滚动时,layout_width属性值设置为match_parent,layout_height属性值设置为
wrap_content。
(2)水平方向滚动时,layout_width属性值设置为wrap_content,layout_height属性值设置为
match_parent。
(3)滚动视图节点下面必须且只能挂着一个子布局节点,否则会在运行时报错Caused by:
java.lang.IllegalStateException:ScrollView can host only one direct child。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <!-- HorizontalScrollView是水平方向的滚动视图,当前高度为200dp -->
    <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="300dp"
                android:layout_height="match_parent"
                android:background="#aaffff" />
            <View
                android:layout_width="300dp"
                android:layout_height="match_parent"
                android:background="#ffff00" />
        </LinearLayout>
    </HorizontalScrollView>
    <!-- ScrollView是垂直方向的滚动视图,当前高度为自适应 -->
    <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>

 

posted on 2024-10-22 09:24  leapss  阅读(17)  评论(0)    收藏  举报