對于使用webview加載一個網頁,使用它的loadurl()方法即可郎嫁,如果在程序內要打開網頁,難么就要自己創(chuàng)建一個WebViewClient,通過setWebViewClient進行關聯(lián)捣炬,再如果網頁里面有javaScript那就要設置了
//啟用支持javascriptWebSettings settings =webView.getSettings();
settings.setJavaScriptEnabled(true);
這都是一系列問題溶弟,但有沒有想過直接寫一個activity,只需傳入url就可以顯示網頁蒲稳,包括解決緩存的使用:
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
后退時的操作:
//改寫物理按鍵——返回的邏輯@OverridepublicbooleanonKeyDown(intkeyCode, KeyEvent event) {//TODO Auto-generated method stubif(keyCode==KeyEvent.KEYCODE_BACK)
{
if(webView.canGoBack())
{
webView.goBack();//返回上一頁面returntrue;
}else{
System.exit(0);//退出程序}
}returnsuper.onKeyDown(keyCode, event);
}
等等一些列問題.
在此就引入了一個相對比較萬能的webview,傳入url即可氮趋,復制就能使用的webview的activity
importandroid.content.Intent;
importandroid.util.Log;
importandroid.view.View;
importandroid.webkit.WebView;
importandroid.widget.TextView;
publicclassWhyWebActivityextendsCanbackWebActivityimplementsView.OnClickListener?{
privateTextView?header_title;
privateString?webPageTitle;
@Override
protectedintgetContentView()?{
returnR.layout.activity_new_web;
}
@Override
protectedWebView?getWebview()?{
return(WebView)?findViewById(R.id.new_web_view);
}
@Override
protectedNumberProgressBar?getProgressbar()?{
return(NumberProgressBar)?findViewById(R.id.new_web_progress_bar);
}
@Override
protectedTextView?getTextViewClose()?{
return(TextView)?findViewById(R.id.header_left_close);
}
@Override
protectedvoidsetTitle(String?urlTitle)?{
Intent?intent?=?getIntent();
if(intent?!=null)?{
webPageTitle?=?intent.getStringExtra("title");
}
if(webPageTitle?!=null&&?!webPageTitle.equals(""))?{
header_title.setText(webPageTitle);
}else{
header_title.setText(urlTitle);
}
}
@Override
protectedvoidonLoadError(WebView?webView,interrorCode,?String?description,?String?failingUrl)?{
}
@Override
protectedvoidonLoadEnd(String?url)?{
}
@Override
protectedvoidinitEnd()?{
webview.loadUrl(getIntent().getStringExtra("url"));//?網址
findViewById(R.id.header_left_btn).setOnClickListener(this);//?返回按鈕點擊事件
header_title?=?(TextView)?findViewById(R.id.header_title);
}
@Override
protectedvoidjsCallJava(MWebviewClient?mWebviewClient)?{
}
@Override
protectedvoidonJsRequest(Object?data)?{
}
@Override
publicvoidonClick(View?v)?{
switch(v.getId())?{
//?點擊關閉頁面
caseR.id.header_left_btn:
onBackPressed();
break;
}
}
}
然后就是父類CanBackWebActivity
packagecn.moviebuff.app.homewall.Web;
importandroid.annotation.SuppressLint;
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.graphics.Bitmap;
importandroid.graphics.Color;
importandroid.net.http.SslError;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.Gravity;
importandroid.view.KeyEvent;
importandroid.view.View;
importandroid.webkit.JavascriptInterface;
importandroid.webkit.SslErrorHandler;
importandroid.webkit.WebChromeClient;
importandroid.webkit.WebSettings;
importandroid.webkit.WebView;
importandroid.widget.TextView;
importandroid.widget.Toast;
importcom.umeng.socialize.ShareAction;
importcom.umeng.socialize.UMShareListener;
importcom.umeng.socialize.bean.SHARE_MEDIA;
importcom.umeng.socialize.media.UMImage;
importorg.json.JSONException;
importorg.json.JSONObject;
importbutterknife.ButterKnife;
publicabstractclassCanbackWebActivityextendsActivity?{
protectedWebView?webview;
protectedNumberProgressBar?progressbar;
protectedTextView?textViewClose;
protectedMWebviewClient?mWebviewClient;
privateString?webTitle;
@Override
publicvoidonCreate(Bundle?savedInstanceState)?{
super.onCreate(savedInstanceState);
initView();
if(null!=?webview?&&null!=?progressbar?&&null!=?textViewClose)?{
iniWebview();
initEnd();
}
}
@Override
publicIntent?getIntent()?{
returnsuper.getIntent();
}
privatevoidinitView()?{
setContentView(getContentView());
ButterKnife.inject(this);
webview?=?getWebview();
progressbar?=?getProgressbar();
textViewClose?=?getTextViewClose();
toastRoot?=?getLayoutInflater().inflate(R.layout.activity_sign,null);
}
protectedabstractintgetContentView();
protectedabstractWebView?getWebview();
protectedabstractNumberProgressBar?getProgressbar();
protectedabstractTextView?getTextViewClose();
protectedabstractvoidsetTitle(String?urlTitle);
protectedabstractvoidonLoadError(WebView?webView,interrorCode,?String?description,?String?failingUrl);
protectedabstractvoidonLoadEnd(String?url);
protectedabstractvoidinitEnd();
protectedabstractvoidjsCallJava(MWebviewClient?mWebviewClient);
protectedabstractvoidonJsRequest(Object?data);
privatestaticfinalString?APP_CACAHE_DIRNAME?="/webcache";
@SuppressLint("SetJavaScriptEnabled")
@SuppressWarnings("deprecation")
privatevoidiniWebview()?{
webview.getSettings().setSupportZoom(false);
webview.getSettings().setBuiltInZoomControls(false);
try{
webview.getSettings().setJavaScriptEnabled(true);
}catch(Exception?e)?{
System.out.println(e);
}
webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);//設置?緩存模式
//?開啟?DOM?storage?API?功能
webview.getSettings().setDomStorageEnabled(true);
//開啟?database?storage?API?功能
webview.getSettings().setDatabaseEnabled(true);
String?cacheDirPath?=?getFilesDir().getAbsolutePath()?+?APP_CACAHE_DIRNAME;
//設置??Application?Caches?緩存目錄
webview.getSettings().setAppCachePath(cacheDirPath);
//開啟?Application?Caches?功能
webview.getSettings().setAppCacheEnabled(true);
webview.setWebChromeClient(newMChormeClient());
mWebviewClient?=newMWebviewClient(webview);
webview.setWebViewClient(mWebviewClient);
progressbar.setProgressTextColor(Color.parseColor("#29b6f6"));
textViewClose.setOnClickListener(newView.OnClickListener()?{
@Override
publicvoidonClick(View?v)?{
finish();
}
});
//?添加js交互接口類,并起別名?webtest
webview.addJavascriptInterface(this,"webtest");
webview.setWebViewClient(newMWebviewClient(webview));
}
protectedclassMWebviewClientextendsWVJBWebViewClient?{
publicMWebviewClient(WebView?webView)?{
//交互
super(webView,newWVJBHandler()?{
@Override
publicvoidrequest(Object?data,?WVJBResponseCallback?callback)?{
JSONObject?outdata?=?(JSONObject)?data;
onJsRequest(outdata);
Intent?intent?=newIntent();
try{
String?act?=?outdata.getString("act");
if(act?!=null)?{
if(act.equals("showToast"))?{
if(outdata.has("str"))?{
String?str?=?outdata.get("str").toString();
if(str?!=null)?{
showToast(str);
//????????????????????????????????????????T.showShort(CanbackWebActivity.this,str);
}
}
}elseif
}
}
}catch(JSONException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
}
});
jsCallJava(this);
}
//加載開始
@Override
publicvoidonPageStarted(WebView?view,?String?url,?Bitmap?favicon)?{
super.onPageStarted(view,?url,?favicon);
}
//加載完成
@Override
publicvoidonPageFinished(WebView?view,?String?url)?{
progressbar.setVisibility(View.GONE);
onLoadEnd(url);
super.onPageFinished(view,?url);
booleanisBack?=?webview.canGoBack();
if(isBack)?{
textViewClose.setVisibility(View.VISIBLE);
}else{
textViewClose.setVisibility(View.GONE);
}
//被點擊的圖片地址為:http://image.moviebuff.cn/images/201609/mem_2016-09-19-10_1474253053_99140.jpg!600-max
//動態(tài)注入js
//?這段js函數的功能就是江耀,遍歷所有的img幾點剩胁,并添加onclick函數,函數的功能是在圖片點擊的時候調用本地java接口并傳遞url過去
view.loadUrl("javascript:(function(){"+
"var?objs?=?document.getElementsByTagName(\"img\");?"+
"for(var?i=0;i
"{"
+"????objs[i].onclick=function()??"+
"????{??"
+"????????webtest.jsInvokeJava(this.src);??"+
"????}??"+
"}"+
"})()");
}
//加載失敗
@Override
publicvoidonReceivedError(WebView?view,interrorCode,?String?description,?String?failingUrl)?{
progressbar.setVisibility(View.GONE);
onLoadError(webView,?errorCode,?description,?failingUrl);
}
@Override
publicvoidonReceivedSslError(WebView?view,?SslErrorHandler?handler,?SslError?error)?{
super.onReceivedSslError(view,?handler,?error);
progressbar.setVisibility(View.GONE);
}
}
@JavascriptInterface
publicvoidjsInvokeJava(String?img)?{
Log.i("ddddddddddsss","被點擊的圖片地址為:"+?img);
}
protectedclassMChormeClientextendsWebChromeClient?{
@Override
publicvoidonProgressChanged(WebView?view,intnewProgress)?{
if(newProgress?==100)?{
progressbar.setVisibility(View.GONE);
}else{
if(progressbar.getVisibility()?!=?View.VISIBLE)?{
progressbar.setVisibility(View.VISIBLE);
}
progressbar.setProgress(newProgress);
}
super.onProgressChanged(view,?newProgress);
}
@Override
publicvoidonReceivedTitle(WebView?view,?String?title)?{
super.onReceivedTitle(view,?title);
webTitle?=?title;
setTitle(title);
}
}
@Override
publicvoidonBackPressed()?{
if(null!=?webview?&&?webview.canGoBack())?{
webview.goBack();
}else{
webview.loadUrl("about:blank");
super.onBackPressed();
}
}
@Override
publicbooleanonKeyDown(intkeyCode,?KeyEvent?event)?{
if(keyCode?==?KeyEvent.KEYCODE_BACK?&&?event.getRepeatCount()?==0)?{
webview.loadUrl("about:blank");
//webView.destroy();
onBackPressed();
returntrue;
}
returnsuper.onKeyDown(keyCode,?event);
}
privatevoidsetShareContent(String?share_text,?String?share_image,?String?share_url,?String?title)?{
finalSHARE_MEDIA[]?displaylist?=newSHARE_MEDIA[]{
SHARE_MEDIA.WEIXIN,?SHARE_MEDIA.WEIXIN_CIRCLE,
SHARE_MEDIA.QQ,?SHARE_MEDIA.QZONE
};
UMImage?localImage?=newUMImage(thisActivity,?R.drawable.ic_launcher);
newShareAction(this).setDisplayList(displaylist)
.withText(share_text)//?摘要
.withTitle(title)//?標題
.withTargetUrl(share_url)//?分享的網址
.withMedia(localImage)//?分享的圖片
.setListenerList(newUMShareListener()?{
@Override
publicvoidonResult(SHARE_MEDIA?platform)?{
T.showShort(thisActivity,"分享成功啦");
}
@Override
publicvoidonError(SHARE_MEDIA?platform,?Throwable?t)?{
T.showShort(thisActivity,"分享失敗啦");
}
@Override
publicvoidonCancel(SHARE_MEDIA?platform)?{
T.showShort(thisActivity,"分享取消了");
}
})
.open();
}
privateView?toastRoot;
privateToast?toast?=null;
privatevoidshowToast(String?msg)?{
TextView?tv?=?(TextView)?toastRoot.findViewById(R.id.TextViewInfo);
if(toast?==null)?{
toast?=newToast(CanbackWebActivity.this);
tv.setText(msg);
}else{
tv.setText(msg);
}
toast.setView(toastRoot);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}
}
剩下就是布局文件里的webview了祥国,這個就不提供了昵观,以上僅供參考,因為所在項目的不同舌稀,部分可能需要自行改改啊犬。
csdn項目地址:http://blog.csdn.net/greatdaocaoren/article/details/54879723