上一篇文章讲到了webview技术方面的优化(没有看到的朋友可以看看http://blog.csdn.net/fkingu007/article/details/44650031),这次进一步完善一下,主要完成状态保留工作,也是解决了我的一个疑问,下面看看如何做到的。
转载请标明文章出处 http://blog.csdn.net/fkingu007/article/details/44675129,尊重原创。
1、 activity意外被杀
上个博文已经说到了,在onSaveInstanceState(Bundle)调用webview.saveState(bundle)保存状态,在onCreate(Bundle saveInstanceState)里通过savedInstanceState == null判断,不为null,即可通过webview.restoreState(bundle)恢复,这里不多讲了。
2、用户正常back
我们都知道back是不会触发onSaveInstanceState()方法的,那么我们就得通过其他途径保存状态了,哈哈,研究发现可以通过webview.getContentHeight(),webview.getSrollY()得到滚动位置所占html页面实际内容长度的比例,由于html加载内容可能显示不完全,getContentHeight()的值很有可能是会变化的,所以我们最好算出这个百分比,下次恢复的时候也根据百分比再滚动,思路有了,代码实现就没问题啦,下面是关键代码:
// 计算当前滚动位置所占网页内容的百分比 private float calculateProgression(WebView content) { float positionTopView = content.getTop(); float contentHeight = content.getContentHeight(); float currentScrollPosition = content.getScrollY(); float percentWebview = (currentScrollPosition - positionTopView) / contentHeight; Log.e(TAG, "positionTopView:"+positionTopView); Log.e(TAG, "contentHeight:"+contentHeight); Log.e(TAG, "currentScrollPosition:"+currentScrollPosition); Log.e(TAG, "percentWebview:"+percentWebview); return percentWebview; }
@Override protected void onDestroy() { mProgressToRestore = calculateProgression(wv); ll.removeAllViews(); wv.stopLoading(); wv.removeAllViews(); wv.destroy(); wv = null; ll = null; super.onDestroy(); }
WebViewClient.onPageFinished()里进行滚动,加一个标志位只跳转一次
@Override public void onPageFinished(WebView view, String url) { // TODO Auto-generated method stub if (mHasToRestoreState && 0<mProgressToRestore) { mHasToRestoreState = false; view.postDelayed(new Runnable() { @Override public void run() { float webviewsize = wv.getContentHeight() - wv.getTop(); float positionInWV = webviewsize * mProgressToRestore; int positionY = (int) (wv.getTop() + positionInWV); wv.scrollTo(0, positionY); } // 延迟一下 }, 100); } super.onPageFinished(view, url); Log.d(TAG, "pageFinished:"+url); }
原文:http://blog.csdn.net/fkingu007/article/details/44675129