【问题标题】:Restore webview scroll position?恢复webview滚动位置?
【发布时间】:2016-10-13 12:19:27
【问题描述】:

我想在用户离开应用程序时保存我的webView 的状态及其页面滚动位置,并在用户再次打开应用程序时恢复它们。这样,用户可以继续阅读恢复的 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");
    }

【问题讨论】:

    标签: android scroll webview


    【解决方案1】:

    您可以在OnDestroy 方法中保存SharedPreferences 中的位置,并在OnCreate 方法中检索它。

    编辑:如here 所述,OnPause 应该是存储数据的地方,而不是OnDestroy

    【讨论】:

    • 对不起,但它没有帮助,因为当用户从最近的应用程序中滑动应用程序时,它不会调用 onDestroy 方法!!!!!!
    • 发布你的 onDestroy 方法,无论如何,你可以将它保存在 OnStop 中,因为可能不会调用 OnDestroy。
    • 我使用了 onStop() 它可以将位置保存在浮点变量中..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多