恢复webview滚动位置?

4

我希望能够在用户离开应用时保存webView的状态,包括页面滚动位置,并在用户再次打开应用时恢复状态。这样,用户就可以继续阅读已恢复的网页内容并滚动到恢复的位置。

以下是我使用的方法:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_book);
    webView = (WebView)this.findViewById(R.id.webView);
    if (savedInstanceState != null) {
        int positionY = Math.round(scrollPos);
        webView.scrollTo(0, positionY);
    } esle {
      //do something
    }

计算位置的函数:

    private int calculateProgression(WebView content) {
    int positionTopView = content.getTop();
    int contentHeight = content.getContentHeight();
    int currentScrollPosition = content.getScrollY();
    int percentWebview = (currentScrollPosition - positionTopView) / contentHeight;
    return percentWebview;
}

保存/恢复函数:

    @Override
    protected void onSaveInstanceState(Bundle outState) {
    outState.putInt("position", calculateProgression(webView));
    super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    scrollPos = savedInstanceState.getFloat("position");
    }
1个回答

1
你可以在OnDestroy方法中将位置保存在SharedPreferences中,并在OnCreate方法中检索它。 编辑: 如此处所述,应该在OnPause中存储数据,而不是在OnDestroy中。

抱歉,这并没有帮助,因为当用户从最近使用的应用中滑动该应用时,它不会调用onDestroy方法!!! - Qassim babyDroid
发布您的onDestroy方法,无论如何,您可以将其保存在OnStop中,因为OnDestroy可能不会被调用。 - Dani M
我使用了onStop()方法,并成功将位置保存在一个浮点变量中。 - Qassim babyDroid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接