Restore webview scroll position?

谁说胖子不能爱 提交于 2020-01-15 11:05:08

问题


I want to save the state of my webView with its page scroll position when user leaves the app and restore them when user opens the app again. So that, user can continue reading the restored webview content scrolled down to the restored position.

Here are methods I'm using:

    @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
    }

Function that calculates the position:

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

save/restore functions:

    @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:


You could save the position in the SharedPreferences in the OnDestroy method and retrieve it in the OnCreate method.

EDIT: As stated here, OnPause should be the place to store data, not OnDestroy.



来源:https://stackoverflow.com/questions/40020820/restore-webview-scroll-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!