How do I add scrollbars to a LinearLayout in Android?

Angel picture Angel · Apr 14, 2011 · Viewed 50.4k times · Source

How do I add scrollbars to a view in Android?

I tried by adding android:scrollbars:"vertical" to the LinearLayout in my layout XML file but it is not working.

I thought scrollbars were drawn by default in Android but it does not seem that way. It seems we have to draw it ourselves - how do I do this?

Answer

Joseph Earl picture Joseph Earl · Apr 14, 2011

You cannot add scrollbars to a LinearLayout because it is not a scrollable container.

Only scrollable containers such as ScrollView, HorizontalScrollView, ListView, GridView, ExpandableListView show scrollbars.

I suggest you place your LinearLayout inside a ScrollView which will by default show vertical scrollbars if there is enough content to scroll.

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >

        <!-- Your content goes here -->   

    </LinearLayout>
</ScrollView>

If you want the vertical scrollbar to always be shown, then add android:scrollbarAlwaysDrawVerticalTrack="true" to your ScrollView. Note the height of the LinearLayout is set to wrap_content - this means the height of the LinearLayout can be larger than that of the ScrollView if there is enough content - in that case you will be able to scroll your LinearLayout up and down.