您的位置:首页 > 移动开发 > 微信开发

[置顶] 微信文章webview记录上次访问位置的实现原理和代码,webview记录并定位到上次访问位置

2016-07-07 11:36 766 查看
大家经常看微信上的公众号文章,可以看到我们每次浏览上次浏览过的文章时,就会定位到上次看到过的位置

这个功能很实用

下面就给大家讲讲它的实现原理,和使用代码,实现起来很简单

实现原理
就是用webview.getScrollY记录你当前的webview已经滑动的位置
下次再进入这个页面时,在网页加载完成时调用:webview.scrollTo(int x, int y)方法即可

实现步骤;

1,用SharedPreferences或者数据库保存当前webview滑动的位置,如果多个页面都要记录访问位置,就需要用
集合把url和位置都保存起来
我们可以在activity的
 @Override

    public void onPause() {

        super.onPause();     

        //CacheUtils是我自己封装的SharedPreferences保存工具类

        //记录上次访问的位置,这里的mArticleContent.aid是我的文章的id,
//当然你可用你的文章url作为key,value为你的webview滑动位置即可

        if (webview != null) {

            int scrollY = webview.getScrollY();

            CacheUtils.putInt(this, mArticleContent.aid, scrollY);//保存访问的位置

        }

    }

2,获取保存的位置,用webview.scrollTo(int x, int y)定位到上次访问的位置
class webviewClient extends WebViewClient {

        @Override

        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            //

        }

        @Override

        public void onPageFinished(WebView view, String url) {

            super.onPageFinished(view, url);
//获取保存的位置position

            int position = CacheUtils.getInt(DetailActivity.this, mArticleContent.aid, 0);

            view.scrollTo(0, position);//webview加载完成后直接定位到上次访问的位置

        }

    }

为了照顾小白,下面贴出我的CacheUtils工具类

public class CacheUtils {
private static final String NAME = "huxiu";
private static SharedPreferences sp = null;

// 存Strings
public static void putString(Context context, String key, String value) {
if (sp == null) {
sp = context.getSharedPreferences(NAME,
Context.MODE_PRIVATE);
}
sp.edit().putString(key, value).commit();
}

// 取String
public static String getString(Context context, String key, String defValue) {
if (sp == null) {
sp = context.getSharedPreferences(NAME,
Context.MODE_PRIVATE);
}
return sp.getString(key, defValue);
}

//存Int值
public static void putInt(Context context, String key, int value) {
if (sp == null) {
sp = context.getSharedPreferences(NAME,
Context.MODE_PRIVATE);
}
sp.edit().putInt(key, value).commit();
}

//取int值
public static int getInt(Context context, String key, int defValue) {
if (sp == null) {
sp = context.getSharedPreferences(NAME,
Context.MODE_PRIVATE);
}
return sp.getInt(key, defValue);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: