Can I scroll a ScrollView programmatically in Android? Can I scroll a ScrollView programmatically in Android? android android

Can I scroll a ScrollView programmatically in Android?


The answer from Pragna does not work always, try this:

mScrollView.post(new Runnable() {         public void run() {              mScrollView.scrollTo(0, mScrollView.getBottom());        } });

or

mScrollView.post(new Runnable() {         public void run() {              mScrollView.fullScroll(mScrollView.FOCUS_DOWN);        } });

if You want to scroll to start

mScrollView.post(new Runnable() {         public void run() {              mScrollView.fullScroll(mScrollView.FOCUS_UP);        } });


ScrollView sv = (ScrollView)findViewById(R.id.scrl);sv.scrollTo(0, sv.getBottom());

or

sv.scrollTo(5, 10);


I wanted the scrollView to scroll directly after onCreateView() (not after e.g. a button click). To get it to work I needed to use a ViewTreeObserver:

mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {        @Override        public void onGlobalLayout() {            mScrollView.post(new Runnable() {                public void run() {                    mScrollView.fullScroll(View.FOCUS_DOWN);                }            });        }    });

But beware that this will be called everytime something gets layouted (e.g if you set a view invisible or similar) so don't forget to remove this listener if you don't need it anymore with:

public void removeGlobalOnLayoutListener (ViewTreeObserver.OnGlobalLayoutListener victim) on SDK Lvl < 16

or

public void removeOnGlobalLayoutListener (ViewTreeObserver.OnGlobalLayoutListener victim) in SDK Lvl >= 16