Last Updated:

ScrollView in Android | With Example

ScrollView — Used to package a hierarchy of View objects into a container that can be scrolled (scrolled).

Scrollview in Android Review

The Scrollview container is a special type of FrameLayout. Its peculiarity is that it allows users to view content that takes up more space than is physically available on the display. In other words, view content that doesn't fit on the screen without scrolling.

A Scrollview can contain only one child element or container.ViewGroup

Tips for using Scrollview

  • Never use a ListView or GridView with a ScrollView. The ListView is designed to display a list of items and is optimized to work with large amounts of data. It also includes built-in capabilities for scrolling through content.
  • The Scrollview container only supports vertical scrolling. If you want to add horizontal scrolling, we'll need another FrameLayout successor, the HorizontalScrollView container.
  • In xml markup, the ScrollView container has a useful property that determines whether a Scrollview should stretch its content to fill the available space on the screen. A method is also available to set this value in code: .android:fillViewportsetFillViewport(boolean)

Example of using Scrollview in Android

 

First of all, let's create a new Android project.

Now let's create a layout in which there will be an ImageView widget with a picture and two TextViews: for the title and text. Wrap all this in a vertical LinearLayout and place it in the root ScrollView (remember that a Scrollview cannot contain more than one child element):

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillviewport="true">


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">


<ImageView
android:layout_width="match_parent"
android:layout_height="212dp"
android:src="YOUR_IMAGE" />


<TextView
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SharedPreferences in Android: Save Preferences"
android:textAppearance="?android:attr/textAppearanceLarge" />


<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Insert a very long text here that needs to scroll" />
</LinearLayout>
</ScrollView>

 

As you can see, we have content that doesn't fit on the screen at once. We put it in the Scrollview container, allowing vertical scrolling across the entire height of the content.