ScrollView in Android with Example

ScrollView-in-Android-with-Example.png

17th March, 2023

Now we are going to learn about another widget of the Android System. It is Android ScrollView.

1. Overview of ScrollView

ScrollView is a Android Widget used to create a scrollable container that can contain any type of view, such as layouts, images, texts. ScrollView provides a way to display content that is larger than the available screen size, and users can scroll through the content to view it.

Android-ScrollView-Sample.gif

Android ScrollView is a useful widget that allows you to create scrollable views in your app.

Note: ScrollView supports only vertical scrolling and HorizontalScrollView supports only horizontal scrolling, so we will use them accordingly.

Note: ScrollView supports only one direct child element. That means we cannot directly add multiple child elements inside a ScrollView. To add multiple child elements inside a listview we need to add a layout (LinearLayout, RelativeLayout, or ConstraintLayout).

2. Create ScrollView in Android Studio

2.1 Create ScrollView in XML layout file

You can drag and drop a ScrollView widget from the palette to your layout in the Design view. Then, you can add your content to the ScrollView by dragging and dropping other widgets inside it.

Add-Create-ScrollView-in-Android-Layout.gif

We have added a ScrollView inside the RelativeLayout. See the code below.

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:text="Hello Androidchunk!" />

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

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

</RelativeLayout>

2.2 Create ScrollView Programmatically in Android

You can also create a ScrollView dynamically in your code using the ScrollView class. For example:

KotlinJava
content_copy light_mode remove
package com.androidchunk.helloscrollview

import android.os.Bundle
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.ScrollView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val parentLayout = findViewById<RelativeLayout>(R.id.parent)

        val myScrollView = ScrollView(this)
        myScrollView.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        // Add your content here

        parentLayout.addView(myScrollView)
    }
}
package com.androidchunk.helloscrollview;

import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RelativeLayout parentLayout = findViewById(R.id.parent);

        ScrollView myScrollView = new ScrollView(this);
        myScrollView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 
                ViewGroup.LayoutParams.MATCH_PARENT));
        // Add your content here
        
        parentLayout.addView(myScrollView);
    }
}

3. Android ScrollView Example

Let’s implement a simple example of Android ScrollView using Kotlin And Java.

Step 3.1: Create New Project

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from the templates.

Step 3.2: Add ScrollView to the XML Layout (UI)

Open the xml layout file and add a ScrollView from the palette. Now the ScrollView is ready to use. By default, Android Studio adds a linear layout with the ScrollView. We can add multiple views on it. Let’s add some views.

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    android:padding="5dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/apple"
        android:textColor="#535353"
        android:textSize="26sp" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/apple" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/details"
        android:textColor="#535353"
        android:textSize="18sp" />

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

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

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/apple_fruit_desc" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

Step 3.3: Image and Strings Resources

We have added an apple image to the drawable folder. This is an optional step.

Android-drawable-Res-Apple-Img-1.png
apple-1.jpg

Strings resource file

XML
content_copy light_mode remove
<resources>
    <string name="app_name">Hello ScrollView</string>
    <string name="apple">Apple</string>
    <string name="details">Details:</string>
    <string name="apple_fruit_desc">Apples are one of the most popular fruits in the world and are consumed widely due to their numerous health benefits. They belong to the Rosaceae family and are scientifically known as Malus domestica.\n\nApples are native to Central Asia but have spread throughout the world, with the United States being the second-largest producer of apples after China.\n\nApples come in a variety of colors, including red, yellow, and green. Red apples are the most common and have a sweet-tart flavor, while green apples are slightly tart and are often used in cooking.\n\nApples are a good source of fiber and vitamin C, and they also contain antioxidants that help protect against diseases like cancer, Alzheimer\'s, and Parkinson\'s.\n\nApples are low in calories, with a medium-sized apple containing approximately 95 calories. They are also low in fat, sodium, and cholesterol, making them a great snack for those trying to maintain a healthy diet.\n\nApples can be eaten raw or cooked and can be used in a variety of recipes, including pies, cakes, and sauces. They are also a popular ingredient in salads, smoothies, and juices.\n\nThere are over 7,500 different types of apples grown worldwide, with each variety having its unique flavor and texture. Some popular varieties include Granny Smith, Honeycrisp, and Red Delicious.\n\nApples are harvested in the fall and can be stored for several months in a cool, dry place. Apples can also be preserved by canning, freezing, or drying.\n\nApple orchards are a popular destination for families during the fall, with many offering activities such as hayrides, apple picking, and cider making.\n\nDespite being a healthy fruit, apples can cause an allergic reaction in some individuals. Symptoms of an apple allergy can include itching, swelling, and difficulty breathing. If you experience these symptoms after consuming apples, it is best to consult a doctor.</string>
</resources>

Run the application and check the output.

Step 3.4: Output

Happy coding!

Leave a Reply