user578386
user578386

Reputation: 1061

HorizontalScrollView can host only one direct child

I ve got a relative Layout and adding imageview programatically in my horizontal scrollview which is placed in xml.when i tried to add my imageview in horizontalScrollView ..i m getting the runtime exception .HorizontalScrollView can host only a single child.could you guys help me out

  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 file

<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>

Upvotes: 6

Views: 11950

Answers (3)

tyczj
tyczj

Reputation: 73836

Meaning, you have to add the imageview to the linearlayout. when you add the image view you are adding it to the HorizontalScrollview which also has a LinearLayout in it ther by adding 2 child elements to the HorizontalScrollView which you cannot do

Upvotes: 7

Bryan Herbst
Bryan Herbst

Reputation: 67209

You should be adding your buttons to your LinearLayout, not directly to the HorizontalScrollView. As the error indicates, a HorizontalScrollView can only have one child.

The best way to do this would be to give your LinearLayout an ID, and reference the LinearLayout in your code instead of the HorizontalScrollView.

Upvotes: 3

CaseyB
CaseyB

Reputation: 25058

The error tells you everything you need. A ScrollView can only have one child and in your layout xml you already have a LinearLayout inside the ScrollView so you just need to add your images to the LinearLayout instead of the ScrollView.

Upvotes: 1

Related Questions