简体   繁体   中英

Resume a scroll view to a position on Onresume

i have a scroll view on my layout and many buttons after scrolling and choosing a button when it returns back to the layout the scroll view starts at the top. i wanted the scroll view to starts from where the user stops. please help am a beginner in android so please explain briefly.

You'll have to save your scroll view's position before your Activity or Fragment gets Destroyed.

You can save value on onSaveInstanceState

//save value on onSaveInstanceState
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putIntArray("SCROLL_POSITION",
            new int[]{ mScrollView.getScrollX(), mScrollView.getScrollY()});
}

and then restore it on onRestoreInstanceState

//Restore them on onRestoreInstanceState
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    final int[] position = savedInstanceState.getIntArray("SCROLL_POSITION");
    if(position != null)
        mScrollView.post(new Runnable() {
            public void run() {
                mScrollView.scrollTo(position[0], position[1]);
            }
        });
}

The above is just an example for more details see THIS BLOG and This post on SO .

The best solution is described here: Link
In few words: You have to support orientation changing, so saving the X and Y position of the scroll bar is no the best solution. Instead you have to get the position of the top visible item and scroll to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM