Android ScrollView


Android ScrollView Tutorials and Examples

A ScrollView is an android layout that permits it's child views to be scrolled vertically. This is important because in many cases you need content to be scrolled. Normally adapterviews like ListView and recyclerview have scrolling capability but not many views. Hence we don't use scrollview with them otherwise we get degraded performance.

With scrollview you only scroll up or down. However if you want horizontal scrolling then you can use the HorizontalScrollView.

Furthermore, ScrollView should only have one direct child. This then means that if you desire to add multiple children then use a ViewGroup like relativelayout or LinearLayout. Then add those children to the viewgroup and the viewgroup to Scrollview.

Android Engineeres are recommending that you use NestedScrollView instead of ScrollView for vertical scrolling.

This is because the latter offers greater user interface flexibility and support for the material design scrolling patterns.

ScrollView API Definition

A scrollview as a class resides in the android.widget package and derives from FrameLayout:

public class ScrollView extends FrameLayout 

Here's the inheritance hierarchy of FrameLayout:

java.lang.Object
   ↳    android.view.View
       ↳    android.view.ViewGroup
           ↳    android.widget.FrameLayout
               ↳    android.widget.ScrollView

Important ScrollView methods

(a). scrollTo(int x, int y)

In this method you pass the scrolled position of your view. This version also clamps the scrolling to the bounds of our child.

    public static void scrollToUp(ScrollView scrollView) {
        scrollView.scrollTo(0, 0);
    } 

(b). smoothScrollTo(int x, int y)

Like scrollTo(int, int), but scroll smoothly instead of immediately.

    public static void smoothScrollToUp(ScrollView scrollView) {
        scrollView.smoothScrollTo(0, 0);
    } 

(c). getChildAt(int index)

This method will return the view at the specified position in the group.

View child = scrollView.getChildAt(0);

(d). getChildCount()

This method returns the number of children in the group.

int count = scrollView.getChildCount();

Quick ScrollView Examples

1. ScrollView - How to Scroll to the Top

Let's see how you can scroll to the top of your scrollview.

    public static void scrollToUp(ScrollView scrollView) {
        scrollView.scrollTo(0, 0);
    } 
2. How to Scroll to Down in ScrollView

Then we want to see also how we can scroll down to the bottom of our scrollview programmatically.

It's a static method and we pass ScrollView instance as a parameter. First we get the height of the scrollview as we as it's child counts.

At the end of the day we are still using the scrollTo() method, passing in the x and y positions.

    public static void scrollToDown(ScrollView scrollView) {
        int y = scrollView.getHeight();
        int count = scrollView.getChildCount();
        if (count > 0) {
            View view = scrollView.getChildAt(count - 1);
            y = view.getBottom() + scrollView.getPaddingBottom();
        } 
        scrollView.scrollTo(0, y);
    } 
3. How to smooth scroll to up

We use the smoothScrollTo() method and pass the positions.

    public static void smoothScrollToUp(ScrollView scrollView) {
        scrollView.smoothScrollTo(0, 0);
    } 
4. How to smooth scroll to Down

Here's how we can scroll to down programmatically.

    public static void smoothScrollToDown(ScrollView scrollView) {
        int y = scrollView.getHeight();
        int count = scrollView.getChildCount();
        if (count > 0) {
            View view = scrollView.getChildAt(count - 1);
            y = view.getBottom() + scrollView.getPaddingBottom();
        } 
        scrollView.smoothScrollTo(0, y);
    } 
5. How to calculate height of ScrollView by Child View
    public static int calculaetHeightByView(ScrollView scrollView, View viewin) {
        int topAll = viewin.getTop();
        ViewParent p = viewin.getParent();
        while (p != null) {
            topAll += ((View) p).getTop();
            if (p instanceof NestedScrollView) {
                break; 
            } 
            p = p.getParent();
        } 
        return topAll;
    } 
6. How to create a scrollview with maximum height limit

What if we desire to set the maximum height limit to our scrollview. Well we can simply create a custom scrollview by deriving from the android.widget.ScrollView class, override our constructors as well as the onMeasure() method.

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;

/** 
 * ScrollView with maximum height limit 
 */ 
public class MaxHeightScrollView extends ScrollView {

    private final MaxSizeHelper mHelper = new MaxSizeHelper();

    public MaxHeightScrollView(Context context) {
        this(context, null);
    } 

    public MaxHeightScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (isInEditMode()) {
            return; 
        } 
        mHelper.init(context, attrs);
    } 

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(mHelper.getMaxHeight(), MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    } 

    public void setMaxHeight(int maxHeight) {
        mHelper.setMaxHeight(maxHeight);
    } 
} 
7. Full ScrollView Example

Let's look a full scrollview example.

(a). MainActivity.java


import android.os.Bundle;
import android.support.v7.app.ActionBarActivity; 
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    private static final String TAG = "Main";
    private ScrollView scrollView;

    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Final Text View textview = ( Text View ) findViewById ( R . id . txt );    
        textView.setText(R.string.content);
        Button btnUp = (Button) findViewById(R.id.btn_up);
        Button btnDown = (Button) findViewById(R.id.btn_down);
        btnUp.setOnClickListener(this);
        btnDown.setOnClickListener(this);

        scrollView = (ScrollView) findViewById(R.id.scroll);
        scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override 
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Log . d ( TAG , "Finger press, Y coordinate:" + scrollView . getScrollY ());   
                        break; 

                    case MotionEvent.ACTION_UP:
                        Log . d ( TAG , "Finger raised, Y coordinate:" + scrollView . getScrollY ());   
                        break; 

                    case MotionEvent.ACTION_MOVE:
                        /** 
                         * scrollView.getScrollY(): vertical distance scrolled by ScrollView 
                         * scrollView.getHeight(): the height of one screen 
                         * scrollView.getChildAt(0).getMeasuredHeight(): the total height of the child tags inside the ScrollView 
                         * Here is the total height of the TextView 
                         * 
                         */ 
                        Log . d ( TAG , "Finger swipe, Y coordinate:" + scrollView . getScrollY () +    
                                ",scrollView.getHeight():" + 
                                scrollView.getHeight() +
                                ",scrollView.getChildAt(0).getMeasuredHeight():" + 
                                scrollView.getChildAt(0).getMeasuredHeight() +
                                ",scrollView.getMeasuredHeight():" + 
                                scrollView.getMeasuredHeight());

                        // Whether to slide to the bottom of the scroll bar: The total height of the TextView <= the height of a screen + 
                        // The vertical distance of the ScrollView scroll 
                        if (scrollView.getChildAt(0).getMeasuredHeight() <= scrollView.getHeight() +
                                scrollView.getScrollY()) {
                            Log . d ( TAG , "Already to the bottom bird!" ); 
                            textView.append(getResources().getString(R.string.content));
                        } 
                } 
                return false; 
            } 
        }); 

    } 

    @Override 
    public void onClick(View v) {

        /** 
         * scrollTo: each time the relative distance is scrolled from the starting (X or Y axis) position 
         * scrollBy: scroll from the last relative position 
         */ 

        switch (v.getId()) {
            case R.id.btn_up:
                scrollView.scrollBy(0, -30);
                break; 
            case R.id.btn_down:
                scrollView.scrollBy(0, 30);
        } 
    } 
} 

(b). activity_main.xml

<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:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_up"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/up"/>
    <Button
        android:id="@+id/btn_down"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/down"/>
    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/txt"
            android:text="@string/hello_world"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    </ScrollView>

</LinearLayout>

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post