Search code examples
androidhorizontalscrollview

HorizontallScrollView with auto-fitting pages


I am trying to create a HorizontalScrollView which will be exactly 3 times the screen width. I have tried the following code, but the scrollview will not scroll. How can I set it so that the 3 LinearLayouts inside the main LinearLayout are each the width of the screen?

<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"

            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true">

<!-- the container for all the pages -->
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="100dp"
       android:background="#000000"/>

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="#FF0000"/>
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="#FF0000"/>
</LinearLayout>

Note that if I give the LinearLayouts a specific width, the scrollview does scroll, but I need each LinearLayout to have the width of the screen.


Solution

  • You will need to use wrap_content on your top LinearLayout, and set the width of the child LinearLayouts programmatically.