Proper way to scroll to a specific row in Android

By xngo on February 21, 2019

Overview

As 1 of the requirements of my Android application, iTransit, it has to automatically scroll to the row of the next bus in the schedule table.

iTransit - Schedule time table

The code

final View row = table.getChildAt(highlightRowPos); // Get the highlighted row.
scrollView.post(new Runnable() {
    @Override
    public void run() {
        scrollView.smoothScrollTo(0, row.getBottom()); // Scroll to the bottom of the row.
    }
});

The table is inside the scrollView. As I create the rows, I record the row positon of the highlighted row and save it in highlightRowPos variable. Then, I proceed to scroll to the highlighted line.

Notice that smoothScrollTo() is wrapped as a runnable and put in the queue through post(). It has to be done this way. Otherwise, row.getBottom() will return 0 and it will not scroll, position=0. By putting the scrolling action in the queue of the UI thread, it allows your action to run in the correct order.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.