恢复 webview 滚动位置? [英] Restore webview scroll position?
问题描述
我想在用户离开应用程序时保存我的 webView
的状态及其页面滚动位置,并在用户打开应用程序时恢复它们再次应用.这样,用户可以继续阅读向下滚动到恢复位置的恢复的 webview 内容.
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
}
计算位置的函数:
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");
}
推荐答案
您可以将位置保存在 SharedPreferences
在 OnDestroy
方法中,并在 OnCreate
方法中检索它.
You could save the position in the SharedPreferences
in the OnDestroy
method and retrieve it in the OnCreate
method.
编辑:如上所述这里,OnPause
应该是存储数据的地方,而不是OnDestroy
.
EDIT: As stated here, OnPause
should be the place to store data, not OnDestroy
.
这篇关于恢复 webview 滚动位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!