Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Programmatically Scroll a ScrollView to Bottom

I've a problem I can't solve: inside a ScrollView I only have a LinearLayout. By a user action I'm programmatically adding 2 TextView on this LinearLayout, but by the default the scroll keeps on the top. Since I controll the user action, I should be easy to scroll to the bottom with something like:

ScrollView scroll = (ScrollView) this.findViewById(R.id.scroll); scroll.scrollTo(0, scroll.getBottom()); 

But actually not. Because immediately after adding this two new elements getBottom() still returns the previous two. I tried to refresh the state invoking refreshDrawableState(), but I doesn't work.

Do you have any idea how could I get the actual bottom of a ScrollView after adding some elements?

like image 565
wikier Avatar asked Nov 04 '11 20:11

wikier


People also ask

How do I scroll to the bottom of the page on Android?

Open a webpage in a browser on your Android device. Make sure the webpage is long enough so that the browser shows a scroll bar. Once there, to get to the bottom of the page, simply tap the top right corner on your device. In the screenshot below, I need to tap the area where the time is shown.

What is ScrollViewReader?

A view that provides programmatic scrolling, by working with a proxy to scroll to known child views.


2 Answers

You need to use the message queue or else it won't work. Try this:

scrollView.post(new Runnable() {     @Override     public void run() {         scrollView.fullScroll(ScrollView.FOCUS_DOWN);     } }); 

This is what worked for me.

like image 175
SBerg413 Avatar answered Oct 07 '22 10:10

SBerg413


This doesn't actually answer your question. But it's an alternative which pretty much does the same thing.

Instead of Scrolling to the bottom of the screen, change the focus to a view which is located at the bottom of the screen.

That is, Replace:

scroll.scrollTo(0, scroll.getBottom()); 

with:

Footer.requestFocus(); 

Make sure you specify that the view, say 'Footer' is focusable.

android:focusable="true" android:focusableInTouchMode="true" 
like image 45
metalwihen Avatar answered Oct 07 '22 10:10

metalwihen