By default when creating android applications, we should always consider the fact that screen sizes for phones vary a lot. Some are short while some are long, with this as a developer you should ensure that the android application you are developing fits all the phone screen sizes either as portrait or landscape. Not only that, one should note that there are contents in android application that seems to be long and can’t fit by default in any screen size, for example, creating an application that displays contact list for a user, this is dependent with the number of people in the contact list and is relative to each user. To ensure that this is fixed without hiding some contents, we use scroll view in android.
Scroll view in android is a view group that allows users to access elements or items that cannot fit in screen size. It only scrolls items that are defined inside the scroll view group. The good thing with scroll view is that you can define a section that you want to scroll and leave others intact.
There is a vertical scroll view that scrolls items in the top-bottom direction and a horizontal scroll view that scrolls items in the left-right direction. The scroll view is a user experience feature meaning it is defined in the XML file.
To include scroll view, the default structure for scroll view is as shown below
// items to scroll will be added here
While adding items to the scroll view, you will need to define your items in a layout and linear layout works best in this (you can review an article in our previous post on relative and linear layouts in android). The code snippet below shows items inside a scroll view.
When you build the app and launch it on a mobile phone and try to scroll, the scroll effect will be visible even if there are no items hidden. You can add as many elements in the scroll view group and notice the scroll view effect.
The above example is the default scroll view effect and scrolls in top bottom direction. To display a scroll view that scrolls in left right direction, android provides a feature called HorizontalScrollView. It is defined as shown below
The horizontal scroll view works the same as the default scroll view apart from that the items scroll from left to right and vice versa. The horizontal scroll view works well with the linear layout which orientation that is set to vertical. You can use the example above and change it to a horizontal scroll view and notice the effect.
In the above explanation, hope you have learned how to use a scroll view in android, the two types of scroll views are the horizontal scroll view and the default scroll view. You can test with many items and notice the effect of scroll view in your mobile device.