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.
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.