自定义webView
package com.jiangmen.zdaiapp.view;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
* ******************************************
*
* File name:MerchantWebView.java
*
* @Author zhsf @Date:2015-11-30
*
* @Description: com.jiangmen.zdaiapp.view.MerchantWebView
*
* ******************************************
*/
public class MerchantWebView extends WebView {
private OnWebViewListener onWebViewListener;
private Context mwContext;
// /**自定义菜单的 按钮*/
// private final int WEB_FenXiang=11;
// private final int WEB_XiaZai=12;
// private final int WEB_FuZhi=13;
// private final int WEB_AddSQ=14;
public interface OnWebViewListener {
public void WebViewOnProgressChanged(WebView view, int newProgress);
}
public void setOnWebViewListener(OnWebViewListener onWebViewListener) {
this.onWebViewListener = onWebViewListener;
}
public MerchantWebView(Context context) {
super(context);
init();
mwContext=context;
}
public MerchantWebView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
mwContext=context;
}
public MerchantWebView(Context context, AttributeSet attrs) {
super(context, attrs);
mwContext=context;
init();
}
// @Override
// public boolean onKeyDown(int keyCode, KeyEvent event) {
// if(keyCode==KeyEvent.KEYCODE_BACK&&canGoBack()){
// goBack();
// return true;
// }
// return super.onKeyDown(keyCode, event);
// }
private void init() {
WebSettings setting = getSettings();
setting.setJavaScriptEnabled(true); // 0
setting.setJavaScriptCanOpenWindowsAutomatically(true);// 允许js弹出窗口
setting.setBuiltInZoomControls(false); // 原网页基础上缩放 //0
setting.setUseWideViewPort(true); // 0
setting.setSupportZoom(false);// 支持缩放 //0
setting.setLoadWithOverviewMode(true);
setting.setDomStorageEnabled(true); // 数据库存储API是否可用,默认值false
setting.setTextZoom(250);
// setting.setLoadsImagesAutomatically(true);// 设置这两项可以上下面两个方法加载有效
setting.setBlockNetworkImage(false); // 是否禁止从网络获取资源,通过http、https URI
setting.setBlockNetworkLoads(false);//Block : 拦截阻塞
setting.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);// 支持内容重新布局
setting.setDisplayZoomControls(false);// 不显示webview缩放按钮1
setPageCacheCapacity(setting);
setWebViewClient(this);
setScrollContainer(false);//禁止内容滑动X-Y;注意看xml的设置
addJavascriptInterface(this, "Resize");
}
private void setWebViewClient(WebView webView) {
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Toast.makeText(mwContext, "onPageStarted="+url, Toast.LENGTH_SHORT).show();
Log.e("onPageStarted", "onPageStarted=="+url);
super.onPageStarted(view, url, favicon);
}
@Override
public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
return super.shouldOverrideKeyEvent(view, event);
}
/*
* 这个方法是,加载url( 你选中的URL )//这里我 打开新的页面进行预览
* */
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// computeHeight();//这个方法,屁股后面总是多出好多空白
// view.loadUrl(url);/这里我 打开新的页面进行预览
Toast.makeText(mwContext, "shouldOverrideUrlLoading="+url, Toast.LENGTH_SHORT).show();
Log.e("shouldOverrideUrlLoading", "shouldOverrideUrlLoading=="+url);
//// 这个方法 没有设置边距; 所以,当有 格式错误的邮件内容显示不完全
// int w = View.MeasureSpec.makeMeasureSpec(0,
// View.MeasureSpec.UNSPECIFIED);
// int h = View.MeasureSpec.makeMeasureSpec(0,
// View.MeasureSpec.UNSPECIFIED);
// //重新测量
// measure(w, h);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
// computeHeight();//这个方法,屁股后面总是多出好多空白
// String text = "我是来自Android";
// view.loadUrl("javascript:carDetail('" + text + "');");
//// 这个方法 没有设置边距;所以,当有 格式错误的邮件内容显示不完全
// int w = View.MeasureSpec.makeMeasureSpec(0,
// View.MeasureSpec.UNSPECIFIED);
// int h = View.MeasureSpec.makeMeasureSpec(0,
// View.MeasureSpec.UNSPECIFIED);
// //重新测量
// measure(w, h);
view.loadUrl("javascript:document.body.style.padding=\"4%\"; void 0");//设置Padding
// Log.e("onPageFinished", "onPageFinished=="+url);
super.onPageFinished(view, url);
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed(); // 接受所有网站的证书
}
@Override
public void onLoadResource(WebView view, String url) {
// TODO Auto-generated method stub
super.onLoadResource(view, url);
}
});
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if (null != onWebViewListener) {
onWebViewListener.WebViewOnProgressChanged(view, newProgress);
}
}
@Override
public void onReceivedTitle(WebView view, String title) {
// Log.e("onReceivedTitle", "onReceivedTitle=="+title);
super.onReceivedTitle(view, title);
}
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
// Log.e("onJsAlert", "onJsAlert=="+url+"message=="+message);
return super.onJsAlert(view, url, message, result);
}
});
// 自定义 长按菜单栏
// webView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener(){
//
// public void onCreateContextMenu(ContextMenu menu, View arg1,
// ContextMenuInfo arg2) {
// // TODO Auto-generated method stub
// MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
// @Override
// public boolean onMenuItemClick(MenuItem item) {
// // do the menu action
// switch (item.getItemId()) {
// case WEB_FenXiang:
// Log.i("you click","分享");
// break;
// case WEB_XiaZai:
// Log.i("you click","下载");
// break;
// case WEB_FuZhi:
// Log.i("you click","复制");
// break;
// case WEB_AddSQ:
// Log.i("you click","增加到书签");
// break;
// }
// return true;
// }};
//
// Log.i("long click","true");
// HitTestResult result = ((WebView) arg1).getHitTestResult();
// int resultType = result.getType();
// if ((resultType == HitTestResult.ANCHOR_TYPE) ||
// (resultType == HitTestResult.IMAGE_ANCHOR_TYPE) ||
// (resultType == HitTestResult.SRC_ANCHOR_TYPE) ||
// (resultType == HitTestResult.SRC_IMAGE_ANCHOR_TYPE)) {
// Intent i = new Intent();
// Log.i("extrea",result.getExtra());
//
// MenuItem item = menu.add(0, WEB_FenXiang, 0, "分享").setOnMenuItemClickListener(handler);
// item.setIntent(i);
// item = menu.add(0, WEB_FuZhi, 0, "复制").setOnMenuItemClickListener(handler);
// item.setIntent(i);
//
// item = menu.add(0,WEB_XiaZai, 0,"下载").setOnMenuItemClickListener(handler); ;
// item.setIntent(i);
//
// item = menu.add(0,WEB_AddSQ, 0,"增加到书签").setOnMenuItemClickListener(handler); ;
// item.setIntent(i);
// menu.setHeaderTitle(result.getExtra());
// }
// else if (resultType == HitTestResult.IMAGE_TYPE) {
// Log.i("image type","ture");
// Intent i = new Intent();
// MenuItem item = menu.add(0, 1, 0, "OPEN");
// item.setIntent(i);
// item = menu.add(0, 2, 0, "图片");
// item.setIntent(i);
// menu.setHeaderTitle(result.getExtra());
// }
// }
// });
// webView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
//
// public void onCreateContextMenu(ContextMenu menu, View arg1,
// ContextMenuInfo arg2) {
// // TODO Auto-generated method stub
// MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
// public boolean onMenuItemClick(MenuItem item) {
// // do the menu action
// switch (item.getItemId()) {
// case 1:
// Log.i("you click", "分享");
// break;
// case 2:
// Log.i("you click", "下载");
// break;
// }
// return true;
// }
// };
//
// HitTestResult result = ((WebView) arg1).getHitTestResult();
// int resultType = result.getType();
// if ((resultType == HitTestResult.IMAGE_TYPE)) {
// menu.setHeaderTitle(result.getExtra());
//
// Intent i = new Intent();
// MenuItem item = menu.add(0, 1, 0, "分享")
// .setOnMenuItemClickListener(handler);
// item.setIntent(i);
//
// item = menu.add(0, 2, 0, "下载").setOnMenuItemClickListener(
// handler);
// item.setIntent(i);
// }
// }
// });
}
private Handler handler = new Handler();
private Runnable runnable;
/**
* 这个方法,屁股后面总是多出好多空白;不行
*/
private void computeHeight() {
loadUrl("javascript:Resize.fetchHeight(document.body.getBoundingClientRect().height)");
}
@JavascriptInterface
public void fetchHeight(final float height) {
final int newHeight = (int) (height * getResources().getDisplayMetrics().density);
runnable = new Runnable() {
@Override
public void run() {
if (getLayoutParams() instanceof LinearLayout.LayoutParams) {
LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) getLayoutParams();
linearParams.height = newHeight;
setLayoutParams(linearParams);
}
}
};
if (null != handler) {
handler.postDelayed(runnable, 50);
}
}
/**
* 当进行goBack的时候 使用前一个页面的缓存 避免每次都重新载入
*
* @param webSettings
* webView的settings
*/
protected void setPageCacheCapacity(WebSettings webSettings) {
try {
Class> c = Class.forName("android.webkit.WebSettingsClassic");
if (null != c) {
Method tt = c.getMethod("setPageCacheCapacity", new Class[] { int.class });
if (null != tt) {
tt.invoke(webSettings, 5);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
调用:
@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
private void initWebView(MerchantWebView webView, String... newContent) {
// WebSettings webSettings=webView.getSettings();
//
// webView.setInitialScale(39); //适应全屏: 39适应竖屏 57适应横屏;0默认的,不做任何修改 ;
//
// webSettings.setJavaScriptEnabled(true);//支持JS,不然下面的不起作用0
// webSettings.setSupportZoom(true);//支持屏幕缩放0
// webSettings.setBuiltInZoomControls(true);//设置WebView可触摸放大缩小0
// webSettings.setDisplayZoomControls(false);//不显示webview缩放按钮
// webSettings.setUseWideViewPort(true);
// //设置双击变大,再双击变小,当手动放大后,双击可以恢复到原始大小,设置如下
// webSettings.setTextZoom(200);//字体大小 WebSettings wb;
//
// String htmlText = "" + "" + "" +
// "";
webView.loadDataWithBaseURL("",
// getHtmlData(msgEmail.getBodyContent().replaceAll(" ",
// " ").replaceAll("\n", "
")),
// ""+ //显示文本内容 style=\"color:#333; font-size:10px;
// color:#F60\"
newContent[0]
// .replaceAll(" ", " ").replaceAll("\n", "
")+
// "" // 4个==一个汉字位 一个空格
, "text/html", "UTF-8", "");
}
清单文件设置: