项目中用到WebView加上进度条放在顶部,让用户知道加载进度情况,可以提高用户体验: 效果:
加载显示进度条.jpg下面我们来实现这个效果:
构造方法
public ProgressWebView(Context context, AttributeSet attrs) { super(context, attrs); mProgressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 8); mProgressBar.setLayoutParams(layoutParams); Drawable drawable = context.getResources().getDrawable( R.drawable.web_progress_bar_states); mProgressBar.setProgressDrawable(drawable); addView(mProgressBar); setWebChromeClient(new WebChromeClient()); }完整ProgressWebView类代码 :
public class ProgressWebView extends WebView { private ProgressBar mProgressBar; public ProgressWebView(Context context, AttributeSet attrs) { super(context, attrs); mProgressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 8); mProgressBar.setLayoutParams(layoutParams); Drawable drawable = context.getResources().getDrawable( R.drawable.web_progress_bar_states); mProgressBar.setProgressDrawable(drawable); addView(mProgressBar); setWebChromeClient(new WebChromeClient()); } public class WebChromeClient extends android.webkit.WebChromeClient { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { mProgressBar.setVisibility(GONE); } else { if (mProgressBar.getVisibility() == GONE) mProgressBar.setVisibility(VISIBLE); mProgressBar.setProgress(newProgress); } super.onProgressChanged(view, newProgress); } } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { LayoutParams lp = (LayoutParams) mProgressBar.getLayoutParams(); lp.x = l; lp.y = t; mProgressBar.setLayoutParams(lp); super.onScrollChanged(l, t, oldl, oldt); } }xml布局引用
<com.aikaifa.webview.ProgressWebView android:id="@+id/baseweb_webview" android:layout_width="match_parent" android:layout_height="match_parent" />其中com.aikaifa.webview 为包名,你可以改成你自己的包名
找到ProgressWebView控件
mWebView = (ProgressWebView) findViewById(R.id.baseweb_webview); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; } }); String url ="http://mp.weixin.qq.com/s?__biz=MzAwODQ5MTA2NQ==&mid=402389923&idx=1&sn=3c89c329e7bf83ce8ff2364726ebd6a7#rd"; mWebView.loadUrl(url);注意一点,不要漏了在AndroidManifest.xml 加上网络权限
<uses-permission android:name="android.permission.INTERNET" />最终效果:
加载中.jpg这样WebView顶部进度条就实现完毕了。