Save the position of scrollview when the orientation changes

后端 未结 6 1663
星月不相逢
星月不相逢 2020-12-02 23:57

These is my layout:

\"detail

I need to save the scrolling position when the orientation change

6条回答
  •  时光说笑
    2020-12-03 00:33

    To save and restore the scroll position of a ScrollView when the phone orientation changes you can do the following: Save the current position in the onSaveInstanceState method:

    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putIntArray("ARTICLE_SCROLL_POSITION",
                new int[]{ mScrollView.getScrollX(), mScrollView.getScrollY()});
    }
    

    Then restore the position in the onRestoreInstanceState method. Note that we need to post a Runnable to the ScrollView to get this to work:

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

    Found this solution on google. Credit goes to Original Coder. :)

提交回复
热议问题