Android中使用HorizontalScrollView横向滑动布局

这篇博客介绍了如何在Android中使用HorizontalScrollView实现横向滚动布局。通过在LinearLayout中嵌套HorizontalScrollView,并添加子控件,如按钮,来展示正确使用HorizontalScrollView的方法。注意,HorizontalScrollView只能有一个直接子View,通常是包含多个子元素的布局容器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Android中,ListView通常用来实现纵向滚动的列表,而HorizontalScrollView则可以实现横向滚动的列表项。

引入HorizontalScrollView控件很简单,例如在一个LinearLayout中:

<LinearLayout 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:orientation="vertical" >

    <HorizontalScrollView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"> 
    </HorizontalScrollView>

</LinearLayout>

这时我们没有添加任何子控件,因此IDE提示我们“This HorizontalScrollView view is useless (no children, no background, no id, no style)

作为示例,我们尝试在这个HorizontalScrollView中添加若干个按钮:

<LinearLayout 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:orientation="vertical"
    tools:context="com.example.viewholdertest.MainActivity" >

    <HorizontalScrollView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello"/>

        ......(余下的省略)

    </HorizontalScrollView>

</LinearLayout>

这时IDE会提示我们:“A scroll view can have only one child”。
原来,在HorizontalScrollView中,只可存在一个直接的子View。因此正确的用法是使用一个如LinearLayout这样的控件,将多个子View放入其中,改好的布局文件是这样的:

<LinearLayout 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:orientation="vertical"
    tools:context="com.example.viewholdertest.MainActivity" >

    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hello" />

            ......(余下的省略)
        </LinearLayout>
    </HorizontalScrollView>
</LinearLayout>

注意HorizontalScrollView中LinearLayout的witdh属性应为”wrap_content”。


现在运行APP,便可以通过横向滑动,将多余的按钮显示出来了。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值