轉載請標明出處:
http://blog.csdn.net/developer_jiangqq/article/details/49687613
本文出自:【江清清的博客】
(一).前言:
【好消息】個人網站已經上線運行,後面博客以及技術乾貨等精彩文章會同步更新,請大家關注收藏:http://www.lcode.org
今天我們來學習一下重寫WebView組件來實現網頁的加載,以及我們平時APP開發中經常使用的JS注入,js和Java相互調用的問題來重點講解一下。如果大家都WebView加載還不是太熟悉的話,這邊我之前專門寫了一個WebView的專題,其他包含基本使用和js注入的問題。(點擊進入WebView進階專題)
FastDev4Android框架項目地址:https://github.com/jiangqqlmj/FastDev4Android
(二).重寫WebView:
2.1首先我們來看一下實現的效果:
2.2.重寫WebView:創建一個HTML5CustomWebView類集成自WebView,然後就是一下幾個步驟實現:
- 佈局文件
- WebSettings初始化相關設置
- 設置重寫WebChromeClient進行相關處理
- 設置重寫WebViewClient進行相關處理即可
簡單的來說就是以上這幾步就可以了
2.3.WebView佈局文件主要定義導航欄,網頁加載進度,以及WebView容器佈局,如下:
- <?xmlversionxmlversion=“1.0” encoding=“utf-8”?>
- <FrameLayoutxmlns:androidFrameLayoutxmlns: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” >
- <!– 自定義頂部導航功能條 –>
- <includelayoutincludelayout=“@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>
<?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);
- }
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);
- }
- }
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();
- }
- }
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
- * 郵箱:[email protected]
- * 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爲空!”);
- }
- }
- }
- }
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
* 郵箱:[email protected]
* 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爲空!”);
- }
- }
- }
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 同時歡迎大家star和fork整個開源快速開發框架項目~
尊重原創,轉載請註明:From Sky丶清(http://blog.csdn.net/developer_jiangqq) 侵權必究!
關注我的訂閱號(codedev123),每天分享移動開發技術(Android/iOS),項目管理以及博客文章!第一時間獲取推送文章!
關注我的微博,可以獲得更多精彩內容