Android Webview添加网页加载进度条实例详解
推荐阅读:AndroidWebView线性进度条实例详解
最近在android项目中使用webview嵌套了一个抽奖活动网页,活动上线,运行良好(改了N次需求和突发bug),还好这种模式的活动,只需要修改网页,不需要重新打包发布市场,这也是这种模式开发的优势之一。后来据产品哥反馈说加载网页无进度提示,好吧,这个当时真没考虑这么多,这个要加加..想当然以为轻松搞定之....其实还是比轻松要复杂点...
1、首先自定义一个WebView控件
/**
*带进度条的Webivew
*@authorlirunzi@.com
*/
@SuppressWarnings("deprecation")
publicclassProgressWebViewextendsWebView{
privatefinalstaticStringTAG=ProgressWebView.class.getSimpleName();
privateProgressBarprogressBar;
privateContextcontext;
publicProgressWebView(Contextcontext,AttributeSetattrs){
super(context,attrs);
this.context=context;
progressBar=newProgressBar(context,null,android.R.attr.progressBarStyleHorizontal);
progressBar.setLayoutParams(newAbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.MATCH_PARENT,,,));
progressBar.setProgressDrawable(getResources().getDrawable(R.drawable.wevbview_progressbar));
addView(progressBar);
setWebChromeClient(newWebChromeClient());
}
publicclassWebChromeClientextendsandroid.webkit.WebChromeClient{
@Override
publicvoidonProgressChanged(WebViewview,intnewProgress){
Log.d(TAG,"newProgress"+newProgress);
if(newProgress==){
progressBar.setVisibility(GONE);
}else{
if(progressBar.getVisibility()==GONE)
progressBar.setVisibility(VISIBLE);
progressBar.setProgress(newProgress);
}
super.onProgressChanged(view,newProgress);
}
//处理javascript中的console.log
@Override
publicbooleanonConsoleMessage(ConsoleMessagecm){
android.util.Log.d(TAG,"webviewconsole"+cm.lineNumber()+"of"+cm.sourceId()+":"+cm.message());
returntrue;
}
//处理javascript中的alert()
@Override
publicbooleanonJsAlert(WebViewview,Stringurl,Stringmessage,JsResultresult){
ToastUtil.showMessage(context,message,Toast.LENGTH_SHORT,Gravity.CENTER);
result.cancel();
returntrue;
}
}
@Override
protectedvoidonScrollChanged(intl,intt,intoldl,intoldt){
LayoutParamslp=(LayoutParams)progressBar.getLayoutParams();
lp.x=l;
lp.y=t;
progressBar.setLayoutParams(lp);
super.onScrollChanged(l,t,oldl,oldt);
}
}
2、在需要使用webview的layout文件中引入这个控件
<cn.net.huami.ui.view.ProgressWebView android:id="@+id/them_webview" android:layout_width="match_parent" android:layout_height="match_parent"/>
3、添加个drawable文件,修改progress控制的进度条样式
<?xmlversion="."encoding="utf-"?> <layer-listxmlns:android="http://schemas.android.com/apk/res/android"> <!--背景--> <itemandroid:id="@android:id/background"> <shape> <solidandroid:color="@color/default_bg"/> </shape> </item> <!--进度条--> <itemandroid:id="@android:id/progress"> <clip> <shape> <solidandroid:color="#EAE"/> </shape> </clip> </item> </layer-list>
4、在activity或fragment中使用这个控件的相关代码
ProgressWebViewwebView=(ProgressWebView)findViewById(R.id.them_webview);
webView.setDownloadListener(newDownloadListener(){
@Override
publicvoidonDownloadStart(Stringurl,StringuserAgent,StringcontentDisposition,Stringmimetype,longcontentLength){
if(url!=null&&url.startsWith("http://"))
startActivity(newIntent(Intent.ACTION_VIEW,Uri.parse(url)));
}
});
webView.loadUrl("网页url");
通过以上代码实现了Webview添加网页加载进度条的相关功能,希望对大家有所帮助。