Android webview 下拉刷新

今天由于业务需要,需要对webview下来刷新,但webview肯定没这功能呀,于是就想,在用xlistview把webview放在头部,下拉webview时,就重新加载webview,但这样说不定,可能照成滑动冲突。于是,在stack overflow找到了不错的解决方案。

SwipeRefreshLayout 是谷歌官方下拉刷新控件,4.0以下的版本需要用到 Android-support-v4.jar包才能用到。
SwipeRefreshLayout 使用起来是非常简单的,只需要在可以滑动的控件外层添加即可,如:WebView、ListView和ScroolView.

demo例子如下:
public class MainActivity extends Activity {

private WebView webView;
private WebSettings webSettings;
private SwipeRefreshLayout swipeLayout;
private String linkUrl="https://www.baidu.com/";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    swipeLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_container);
    // 设置刷新监听器
    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            //重新刷新页面
            // webview.loadUrl(webview.getUrl());
            webView.reload();
        }
    });

    //设置进度条渐变的颜色
    swipeLayout.setColorScheme(R.color.holo_blue_bright,
            R.color.holo_green_light, R.color.holo_orange_light,
            R.color.holo_red_light);

    //初始化webview
    initwebview();
}

private void initwebview(){
    webView= (WebView) findViewById(R.id.webview);
    webSettings= webView.getSettings();
    webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    webSettings.setSupportZoom(false);
    webSettings.setBuiltInZoomControls(false);
    webSettings.setAppCacheMaxSize(1024 * 1024 * 9);// 设置缓冲大小
    webSettings.setAllowFileAccess(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });

    //设置进度条
    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                //隐藏进度条
                swipeLayout.setRefreshing(false);
            } else {
                if (!swipeLayout.isRefreshing())
                    //显示进度条
                    swipeLayout.setRefreshing(true);
            }

            super.onProgressChanged(view, newProgress);
        }
    });
    webView.loadUrl(linkUrl);
}

}

你可能感兴趣的:(Android)