简体   繁体   English

将滚动视图恢复到Onresume上的某个位置

[英]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. 请帮助是Android的初学者,所以请简要说明。

You'll have to save your scroll view's position before your Activity or Fragment gets Destroyed. 在销毁“活动”或“片段”之前,您必须保存滚动视图的位置。

You can save value on onSaveInstanceState 您可以在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 然后在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 . 上面只是一个示例,有关更多详细信息,请参见THIS BLOGSO上的这篇文章

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. 简而言之:您必须支持方向更改,因此保存滚动条的X和Y位置并不是最佳解决方案。 Instead you have to get the position of the top visible item and scroll to it. 相反,您必须获取顶部可见项目的位置并滚动到该位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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