Restore scroll position of webview?

I want to save the state of the page of the page when the user leaves the app and restore it when the user opens the application again. Thus, the user can continue reading the restored contents of the web pages scrolled to the restored position.

Here are the methods I use:

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

The 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");
    }
0
source share
1 answer

You can save the position in SharedPreferencesin the method OnDestroyand get it in the method OnCreate.

EDIT: , OnPause , OnDestroy.

0

Source: https://habr.com/ru/post/1664916/


All Articles