6

我有一个相对布局,并以编程方式在我的水平滚动视图中添加图像视图,该滚动视图放置在 xml 中。当我试图在水平滚动视图中添加我的图像视图时 ..我得到运行时异常。水平滚动视图只能托管一个孩子。你们能帮帮我吗出去

  RelativeLayout.LayoutParams HParams = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        HParams.topMargin = 200 * displayHeight / 480;
        HsrollView.setLayoutParams(HParams);

         for (int i = 0; i < 4; i++) { 
             ImageView btnTag = new ImageView(this);
             btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
             btnTag.setImageResource(R.drawable.book);
             btnTag.setTag(i);
             btnTag.setId(i);
             HsrollView.addView(btnTag);
         }

XML 文件

<RelativeLayout 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:background="@drawable/directbg"
    tools:context=".DirectorActivity" >
    <HorizontalScrollView
        android:id="@+id/Hscrollview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:scrollbars="none">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
        </LinearLayout>
    </HorizontalScrollView>
    </RelativeLayout>
4

3 回答 3

7

这意味着,您必须将图像视图添加到线性布局。当您添加图像视图时,您正在将其添加到HorizontalScrollview其中也有一个LinearLayout通过将 2 个子元素添加到您无法执行的 Horizo​​ntalScrollView

于 2013-06-05T14:55:57.717 回答
3

您应该将按钮添加到您的LinearLayout,而不是直接添加到HorizontalScrollView. 如错误所示, aHorizontalScrollView只能有一个孩子。

最好的方法是给你LinearLayout一个 ID,并LinearLayout在你的代码中引用而不是HorizontalScrollView.

于 2013-06-05T14:55:25.167 回答
1

该错误会告诉您所需的一切。AScrollView只能有一个孩子,并且在您的布局 xml 中您已经有一个LinearLayout内部的,ScrollView因此您只需将图像添加到LinearLayout而不是ScrollView.

于 2013-06-05T14:55:15.917 回答