wikier
wikier

Reputation: 2566

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?

Upvotes: 65

Views: 87126

Answers (7)

Kushal Prajapati
Kushal Prajapati

Reputation: 55

I Hope it Work

Try this:

nsscroll.post(new Runnable() { @Override

                    public void run() {

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

                    }
                });

Upvotes: -1

Sunny Jha
Sunny Jha

Reputation: 121

Since, I am also using hide keyboard, below code with a delay of 200 milli second worked better for me. Note: I just replaced post() with postDelayed() from above examples:

    final ScrollView scrollView_main = (ScrollView) findViewById(R.id.scrollView_main);
    scrollView_main.postDelayed(new Runnable() {
        @Override
        public void run() {
            scrollView_main.fullScroll(View.FOCUS_DOWN);
        }
    }, 200);

Upvotes: 2

Steve Bergamini
Steve Bergamini

Reputation: 14600

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.

Upvotes: 151

Aalishan Ansari
Aalishan Ansari

Reputation: 661

you can apply this also

 mScrollviewHomepage.setScrollY(View.FOCUS_DOWN);

Upvotes: 0

metalwihen
metalwihen

Reputation: 1083

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"

Upvotes: 86

sxk
sxk

Reputation: 261

this will be ok

scrollView.post(new Runnable() {
    @Override

    public void run() {

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

    }
});

Upvotes: 21

TotoroTotoro
TotoroTotoro

Reputation: 17612

Have you tried scroll.fullScroll(View.FOCUS_DOWN)?

Upvotes: 5

Related Questions