Restore webview scroll position?

2019-09-07 02:47发布

问题:

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.