Android水平滚动视图

9

我是Android开发的初学者,我想创建一个水平滚动视图,其中包含不同的布局。

我遇到的错误是:水平滚动视图只能容纳一个直接子项。

请提供建议,谢谢!

<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tool"
        android:id="@+id/horizontalScrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:fillViewport="true" >

         <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:orientation="horizontal"
            android:background="#ff0000">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:orientation="horizontal"
                android:background="#ff0000">

            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:orientation="horizontal"
                android:background="#00ff00">

            </LinearLayout>

        </LinearLayout>

    </HorizontalScrollView>

1
你能更精确地定义你的问题吗?你所说的不同布局是什么意思? - Aleksandar Stojadinovic
重点是这个布局没有任何问题。一切都被正确地封装了起来。所有内容都在一个LinearLayout中,正如应该的那样,它位于HorizontalScrollView中。无论您在那个LinearLayout中放置多少东西,它们都会左右滚动。 - Aleksandar Stojadinovic
它可能是模拟器的问题吗? - mr. x
也许模拟器并不完美。ScrollView布局只有当它们的内容超出屏幕边界时才会生效。如果所有内容都适合一个屏幕,它们就什么也不做。如果您看到了原始问题中写的错误,请尝试重新启动IDE。我没有看到那个错误,并且我复制了原样的代码。它甚至在我的手机上运行,我放了一些按钮。 - Aleksandar Stojadinovic
非常感谢你,我会尽快购买设备的,真的非常感谢你的帮助。 - mr. x
显示剩余2条评论
2个回答

11

不仅是水平滚动视图,任何垂直滚动视图也会出现此错误。 该错误意味着一个滚动视图只能有一个子项,并且该子项可以包含任意数量的子子项。

因此,底线是你应该只让滚动视图有一个直接的子项,并在该子项中创建你的布局,如下:

  <HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tool"
    android:id="@+id/horizontalScrollView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true" >

     <LinearLayout

        android:id="@+id/directchild"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:orientation="horizontal"
        android:background="#ff0000">

    </LinearLayout>

</HorizontalScrollView>

现在在直接子布局中创建您想要的布局。这样,您将不会收到任何错误。


其他布局已经是这个主布局的子布局,而不是滚动视图的子布局。 - mr. x
这在我的Eclipse上没有显示任何错误。如果您想看到效果,请为不同的布局设置宽度,并将fillparent宽度应用于主布局,您将看到滚动效果。 - Saurabh

0

嗨,这个错误是因为ScrollView只能托管直接子级。 使用相对布局或线性布局,并将所有布局写在其中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接