## (一).前言:
今天我們來學習一下重寫WebView組件來實現網頁的加載,以及我們平時APP開發中經常使用的JS注入,js和java相互調用的問題來重點講解一下。如果大家都WebView加載還不是太熟悉的話,這邊我之前專門寫了一個WebView的專題,其他包含基本使用和js注入的問題。[(點擊進入WebView進階專題)](http://blog.csdn.net/column/details/adandroid.html)
FastDev4Android框架項目地址:[https://github.com/jiangqqlmj/FastDev4Android](https://github.com/jiangqqlmj/FastDev4Android)
## (二).重寫WebView:
2.1首先我們來看一下實現的效果:

2.2.重寫WebView:創建一個HTML5CustomWebView類集成自WebView,然后就是一下幾個步驟實現:
* ?布局文件
* ?WebSettings初始化相關設置
* ?設置重寫WebChromeClient進行相關處理
* 設置重寫WebViewClient進行相關處理即可
簡單的來說就是以上這幾步就可以了
2.3.WebView布局文件主要定義導航欄,網頁加載進度,以及WebView容器布局,如下:
~~~
<?xmlversion="1.0" encoding="utf-8"?>
<FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="@+id/fullscreen_custom_content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white"
android:visibility="gone"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- 自定義頂部導航功能條 -->
<includelayout="@layout/common_top_bar_layout" />
<!-- 中間顯示內容 -->
<FrameLayout
android:id="@+id/main_content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone" />
<!-- 網頁加載進度顯示 -->
<FrameLayout
android:id="@+id/frame_progress"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="visible" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical" >
<ProgressBar
style="@android:style/Widget.ProgressBar.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:indeterminate="false"
android:indeterminateDrawable="@drawable/loading_small" />
<TextView
android:id="@+id/webview_tv_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dip"
android:text="正在加載,已完成0%..."
android:textSize="12sp" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</RelativeLayout>
</FrameLayout>
~~~
2.4.WebSettings初始化設置如下:
~~~
WebSettingswebSettings = this.getSettings();
webSettings.setJavaScriptEnabled(true); //開啟javascript
webSettings.setDomStorageEnabled(true); //開啟DOM
webSettings.setDefaultTextEncodingName("utf-8");//設置編碼
// // web頁面處理
webSettings.setAllowFileAccess(true);// 支持文件流
// webSettings.setSupportZoom(true);// 支持縮放
// webSettings.setBuiltInZoomControls(true);// 支持縮放
webSettings.setUseWideViewPort(true);// 調整到適合webview大小
webSettings.setLoadWithOverviewMode(true);//調整到適合webview大小
webSettings.setDefaultZoom(ZoomDensity.FAR);//屏幕自適應網頁,如果沒有這個,在低分辨率的手機上顯示可能會異常
webSettings.setRenderPriority(RenderPriority.HIGH);
//提高網頁加載速度,暫時阻塞圖片加載,然后網頁加載好了,在進行加載圖片
webSettings.setBlockNetworkImage(true);
//開啟緩存機制
webSettings.setAppCacheEnabled(true);
//根據當前網頁連接狀態
if(StrUtils.getAPNType(context)==StrUtils.WIFI){
//設置無緩存
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
}else{
//設置緩存
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
~~~
2.5.WebChromeClient進行相關設置處理
~~~
private classMyWebChromeClient extends WebChromeClient {
privateBitmap mDefaultVideoPoster;
@Override
publicvoid onShowCustomView(View view,
CustomViewCallbackcallback) {
super.onShowCustomView(view,callback);
HTML5CustomWebView.this.setVisibility(View.GONE);
if(mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomViewContainer.addView(view);
mCustomView= view;
mCustomViewCallback= callback;
mCustomViewContainer.setVisibility(View.VISIBLE);
}
@Override
publicvoid onHideCustomView() {
if(mCustomView == null) {
return;
}
mCustomView.setVisibility(View.GONE);
mCustomViewContainer.removeView(mCustomView);
mCustomView= null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
HTML5CustomWebView.this.setVisibility(View.VISIBLE);
super.onHideCustomView();
}
/**
* 網頁加載標題回調
* @param view
* @param title
*/
@Override
publicvoid onReceivedTitle(WebView view, String title) {
Log.d("zttjiangqq", "當前網頁標題為:" + title);
wv_tv_title.setText(title);
}
/**
* 網頁加載進度回調
* @param view
* @param newProgress
*/
@Override
publicvoid onProgressChanged(WebView view, int newProgress) {
// 設置進行進度
((Activity)mContext).getWindow().setFeatureInt(
Window.FEATURE_PROGRESS,newProgress * 100);
webview_tv_progress.setText("正在加載,已完成" +newProgress + "%...");
webview_tv_progress.postInvalidate(); //刷新UI
Log.d("zttjiangqq", "進度為:" + newProgress);
}
@Override
publicboolean onJsAlert(WebView view, String url, String message,
JsResultresult) {
returnsuper.onJsAlert(view, url, message, result);
}
}
~~~
2.6.WebViewClient進行相關設置處理
~~~
private classMyWebViewClient extends WebViewClient {
/**
*加載過程中 攔截加載的地址url
* @param view
*@param url 被攔截的url
* @return
*/
@Override
publicboolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i("zttjiangqq","-------->shouldOverrideUrlLoading url:" + url);
//這邊因為考慮到之前項目的問題,這邊攔截的url過濾掉了zttmall://開頭的地址
//在其他項目中 大家可以根據實際情況選擇不攔截任何地址,或者有選擇性攔截
if(!url.startsWith("zttmall://")){
UrimUri = Uri.parse(url);
List<String>browerList = new ArrayList<String>();
browerList.add("http");
browerList.add("https");
browerList.add("about");
browerList.add("javascript");
if(browerList.contains(mUri.getScheme())) {
returnfalse;
}else {
Intentintent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addCategory(Intent.CATEGORY_BROWSABLE);
//如果另外的應用程序WebView,我們可以進行重用
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Browser.EXTRA_APPLICATION_ID,
FDApplication.getInstance()
.getApplicationContext().getPackageName());
try{
FDApplication.getInstance().startActivity(intent);
returntrue;
}catch (ActivityNotFoundException ex) {
}
}
returnfalse;
}else{
returntrue;
}
}
/**
* 頁面加載過程中,加載資源回調的方法
* @param view
* @param url
*/
@Override
publicvoid onLoadResource(WebView view, String url) {
super.onLoadResource(view,url);
Log.i("zttjiangqq","-------->onLoadResource url:" + url);
}
/**
* 頁面加載完成回調的方法
* @param view
* @param url
*/
@Override
publicvoid onPageFinished(WebView view, String url) {
super.onPageFinished(view,url);
Log.i("zttjiangqq","-------->onPageFinished url:" + url);
if(isRefresh) {
isRefresh= false;
}
// 加載完成隱藏進度界面,顯示WebView內容
frame_progress.setVisibility(View.GONE);
mContentView.setVisibility(View.VISIBLE);
// 關閉圖片加載阻塞
view.getSettings().setBlockNetworkImage(false);
}
/**
* 頁面開始加載調用的方法
* @param view
* @param url
* @param favicon
*/
@Override
publicvoid onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d("zttjiangqq","onPageStarted:-----------"+url);
super.onPageStarted(view,url, favicon);
}
@Override
publicvoid onReceivedError(WebView view, int errorCode,
Stringdescription, String failingUrl) {
super.onReceivedError(view,errorCode, description, failingUrl);
}
@Override
publicvoid onScaleChanged(WebView view, float oldScale, float newScale) {
super.onScaleChanged(view,oldScale, newScale);
HTML5CustomWebView.this.requestFocus();
HTML5CustomWebView.this.requestFocusFromTouch();
}
}
~~~
以上一般使用到得方法已經做了相關的注釋。
最后一步就是使用了,使用起來很簡單,創建一個Activity,然后把我們定義的WebView加入到布局然后加載網頁即可。如下:
~~~
packagecom.chinaztt.fda.html5;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.content.res.Configuration;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.view.KeyEvent;
importandroid.view.MotionEvent;
importandroid.webkit.DownloadListener;
importandroid.webkit.JavascriptInterface;
/**
* 當前類注釋:
* 項目名:FastDev4Android
* 包名:com.chinaztt.fda.html5
* 作者:江清清 on 15/11/06 08:59
* 郵箱:jiangqqlmj@163.com
* QQ: 781931404
* 公司:江蘇中天科技軟件技術有限公司
*/
importcom.chinaztt.fda.ui.base.BaseActivity;
public classHTML5WebViewCustomAD extends BaseActivity {
privateHTML5CustomWebView mWebView;
//http://www.zttmall.com/Wapshop/Topic.aspx?TopicId=18
privateString ad_url = "http://www.baidu.com/";
private String title="百度一下你就知道";
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebView= new HTML5CustomWebView(this, HTML5WebViewCustomAD.this,title,ad_url);
mWebView.setDownloadListener(newDownloadListener() {
@Override
publicvoid onDownloadStart(String url, String userAgent,
StringcontentDisposition, String mimetype,
longcontentLength) {
Uriuri = Uri.parse(url);
Intentintent = new Intent(Intent.ACTION_VIEW, uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
//準備javascript注入
mWebView.addJavascriptInterface(
newJs2JavaInterface(),"Js2JavaInterface");
if(savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
}else {
if(ad_url != null) {
mWebView.loadUrl(ad_url);
}
}
setContentView(mWebView.getLayout());
}
@Override
publicvoid onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(mWebView != null) {
mWebView.saveState(outState);
}
}
@Override
protectedvoid onResume() {
super.onResume();
if(mWebView != null) {
mWebView.onResume();
}
}
@Override
publicvoid onStop() {
super.onStop();
if(mWebView != null) {
mWebView.stopLoading();
}
}
@Override
protectedvoid onPause() {
super.onPause();
if(mWebView != null) {
mWebView.onPause();
}
}
@Override
protectedvoid onDestroy() {
super.onDestroy();
if(mWebView != null) {
mWebView.doDestroy();
}
}
@Override
publicvoid onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
publicboolean onTouchEvent(MotionEvent event) {
returnsuper.onTouchEvent(event);
}
@Override
publicboolean onKeyDown(int keyCode, KeyEvent event) {
returnsuper.onKeyDown(keyCode, event);
}
@Override
publicvoid onBackPressed() {
if(mWebView != null) {
if(mWebView.canGoBack()){
mWebView.goBack();
}else{
mWebView.releaseCustomview();
}
}
super.onBackPressed();
}
/**
* JavaScript注入回調
*/
publicclass Js2JavaInterface {
privateContext context;
privateString TAG = "Js2JavaInterface";
@JavascriptInterface
publicvoid showProduct(String productId){
if(productId!=null){
//進行跳轉商品詳情
showToastMsgShort("點擊的商品的ID為:" +productId);
}else{
showToastMsgShort("商品ID為空!");
}
}
}
}
~~~
## (三).js注入方法:
仔細查看上面的代碼可能大家會發現這樣兩塊地方:
~~~
mWebView.addJavascriptInterface(
newJs2JavaInterface(),"Js2JavaInterface");
~~~
~~~
public classJs2JavaInterface {
privateContext context;
privateString TAG = "Js2JavaInterface";
@JavascriptInterface
publicvoid showProduct(String productId){
if(productId!=null){
//進行跳轉商品詳情
showToastMsgShort("點擊的商品的ID為:" +productId);
}else{
showToastMsgShort("商品ID為空!");
}
}
}
~~~
這邊就是js注入回調處理的方法,在這邊的實例中是使用http://www.zttmall.com/Wapshop/Topic.aspx?TopicId=18這個地址進行加載網頁的時候才會生效,因為這邊點擊網頁圖片的時候,html代碼中加載js方法,
我們來看一下網頁的源代碼:

查看源代碼我們就知道
mWebView.addJavascriptInterface(
newJs2JavaInterface(),"Js2JavaInterface");
中第二個參數就是在js方法中調用的對象名字,然后注入對象中回調的方法和js方法中的方法一樣即可。這樣就完成了一次注入點擊回調工作,我們的html就可以和原生java代碼發生交互了。使用這種方式非常有助于我們的混合開發。
??????好了到此重寫WebView實現以及js注入的基本使用就講完了,具體全部代碼已經上傳到FastDev4Android項目中了。同時歡迎大家去Github站點進行clone或者下載瀏覽:
[https://github.com/jiangqqlmj/FastDev4Android](https://github.com/jiangqqlmj/FastDev4Android)?同時歡迎大家star和fork整個開源快速開發框架項目~
- 前言
- Android快速開發框架介紹(一)
- Android首頁圖片自動無限循環輪播Gallery+FlowIndicator(二)
- Android 列表下拉刷新組件PullToRefreshListView使用(三)
- Android 數據緩存器ACache的詳解和使用(四)
- Android崩潰異常捕捉CustomCrash,提升用戶體驗(五)
- Android實現沉浸式狀態欄(六)
- AndroidAnnnotations注入框架介紹和Android Studios基本配置(七)
- AndroidAnnnotations注入框架的工作原理(八)
- AndroidAnnnotations注入框架使用之注入組件Components(九)
- AndroidAnnnotations注入框架使用之Injection標簽詳解(十)
- AndroidAnnnotations注入框架使用之事件綁定Event Binding(十一)
- AndroidAnnnotations注入框架使用之線程處理Threading(十二)
- AndroidAnnnotations注入框架使用之第三方框架集成RoboGuice(十三)
- AndroidAnnnotations注入框架使用之第三方框架集成Otto事件總線(十四)
- AndroidAnnnotations注入框架使用之第三方框架集成OrmLite(十五)
- AndroidAnnnotations注入框架使用之最佳實踐之Adapters和lists(十六)
- AndroidAnnnotations注入框架使用之最佳實踐SharedPreferences(十七)
- Android MVP開發模式詳解(十九)
- 消息總線EventBus的基本使用(二十)
- 消息總線EventBus源碼分析以及與Otto框架對比(二十一)
- 列表頭生成帶文本或者字母的圖片開源庫TextDrawable使用和詳解(二十二)
- 重寫WebView網頁加載以及JavaScript注入詳解(二十三)
- BaseAdapterHelper的基本使用介紹,讓你擺脫狂寫一堆Adapter煩惱(二十四)
- BaseAdapterHelper詳解源碼分析,讓你擺脫狂寫一堆Adapter煩惱(二十五)
- Volley完全解析之基礎使用(二十六)
- Volley完全解析之進階最佳實踐與二次封裝(二十七)
- RecyclerView完全解析,讓你從此愛上它(二十八)
- RecyclerView完全解析之打造新版類Gallery效果(二十九)
- RecyclerView完全解析之結合AA(Android Annotations)注入框架實例(三十)
- RecyclerView完全解析之下拉刷新與上拉加載SwipeRefreshLayout(三十一)
- CardView完全解析與RecyclerView結合使用(三十二)
- 神器ViewDragHelper完全解析,媽媽再也不擔心我自定義ViewGroup滑動View操作啦~(三十三)
- 神器ViewDragHelper完全解析之詳解實現QQ5.X側滑酷炫效果(三十四)
- 實例解析之SwipeRefreshLayout+RecyclerView+CardView(三十五)
- HorizontalScrollView,Fragment,FragmentStatePagerAdapter打造網易新聞Tab及滑動頁面效果(三十六)
- Android Design支持庫TabLayout打造仿網易新聞Tab標簽效果(三十七)
- 打造QQ6.X最新版本側滑界面效果(三十八)