Android HorizontalScrollView must be used when app content might be longer than device width. Android HorizontalScrollView makes content horizontally scrollable.
Android HorizontalScrollView can have only one direct child so if there are more than one child then each child must be wraped in a container like Layout.
In this tutorial, we are going to discuss following things:
Android HorizontalScrollView simple usage in xml layout is given below:
android:fillViewport specify whether the HorizontalScrollView should stretch its content to fill the viewport or not. It can have true or false as its value.
android:fillViewport to true means this will make the subviews occupy the whole space of the ScrollView
android:scrollbarFadeDuration attribute of Android HorizontalScrollView define the delay in milliseconds that a scrollbar takes to fade out. Must be an integer value in milisecond.
android:scrollbarDefaultDelayBeforeFade attribute of Android HorizontalScrollView define delay in milliseconds that a scrollbar waits before fade out. Must be an integer value in milisecond.
android:scrollbarAlwaysDrawHorizontalTrack attribute of Android HorizontalScrollView define whether the horizontal scrollbar track should always be drawn. It can have true or false as its value.
android:scrollbarThumbHorizontal attribute of Android HorizontalScrollView define the horizontal scrollbar thumb drawable.
android:scrollbarTrackHorizontal attribute of Android HorizontalScrollView define the horizontal scrollbar track drawable.
We can define HorizontalScrollView track and thumb in drawable xml.
HorizontalScrollView track drawable I used for this sample is given below:
ScrollBar thumb drawable I used for this sample is given below:
Now, set android:scrollbarThumbHorizontal and android:scrollbarTrackHorizontal of HorizontalScrollBar xml layout as follows:
In this example, We discussed different aspect of Android HorizontalScrollView. Now lets implement a demo for Android HorizontalScrollView
Step 1: Create a new project in Android Studio and name it Android HorizontalScrollView.
Step 2: Open res -> drawable and add six images named nature_1.jpg, nature_2.jpg, nature_3.jpg, nature_4.jpg, nature_5.jpg and nature_6.jpg
Step 3: Open res -> drawable and add a file track.xml, replace its code with below given code:
Step 4: Open res -> drawable and add a file thumb.xml, replace its code with below given code:
Step 5: Open res -> layout -> activity_main.xml and add following code
Step 6: Open your MainActivity.java and replace its source with source of my MainActivity.java as follows:
Step 7: Clean and run the project to see the result.