//启用支持JavascriptWebSettings settings = webView.getSettings();settings.setJavaScriptEnabled(true);
这都是一系列问题,但有没有想过直接写一个activity,只需传入url就可以显示网页,包括解决缓存的使用:
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);后退时的操作://改写物理按键——返回的逻辑 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if(keyCode==KeyEvent.KEYCODE_BACK) {if(webView.canGoBack()) { webView.goBack();//返回上一页面 return true; } else { System.exit(0);//退出程序 } } return super.onKeyDown(keyCode, event); }等等一些列问题.在此就引入了一个相对比较万能的webview,传入url即可,复制就能使用的webview的activityimport android.content.Intent;import android.util.Log;import android.view.View;import android.webkit.WebView;import android.widget.TextView;public class WhyWebActivity extends CanbackWebActivity implements View.OnClickListener { PRivate TextView header_title; private String webPageTitle; @Override protected int getContentView() { return R.layout.activity_new_web; } @Override protected WebView getWebview() { return (WebView) findViewById(R.id.new_web_view); } @Override protected NumberProgressBar getProgressbar() { return (NumberProgressBar) findViewById(R.id.new_web_progress_bar); } @Override protected TextView getTextViewClose() { return (TextView) findViewById(R.id.header_left_close); } @Override protected void setTitle(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 protected void onLoadError(WebView webView, int errorCode, String description, String failingUrl) { } @Override protected void onLoadEnd(String url) { } @Override protected void initEnd() { webview.loadUrl(getIntent().getStringExtra("url")); // 网址 findViewById(R.id.header_left_btn).setOnClickListener(this); // 返回按钮点击事件 header_title = (TextView) findViewById(R.id.header_title); } @Override protected void jsCallJava(MWebviewClient mWebviewClient) { } @Override protected void onJsRequest(Object data) { } @Override public void onClick(View v) { switch (v.getId()) { // 点击关闭页面 case R.id.header_left_btn: onBackPressed(); break; } }}然后就是父类CanBackWebActivitypackage cn.moviebuff.app.homewall.Web;import android.annotation.SuppressLint;import android.app.Activity;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.Color;import android.net.http.SslError;import android.os.Bundle;import android.util.Log;import android.view.Gravity;import android.view.KeyEvent;import android.view.View;import android.webkit.JavascriptInterface;import android.webkit.SslErrorHandler;import android.webkit.WebChromeClient;import android.webkit.WebSettings;import android.webkit.WebView;import android.widget.TextView;import android.widget.Toast;import com.umeng.socialize.ShareAction;import com.umeng.socialize.UMShareListener;import com.umeng.socialize.bean.SHARE_MEDIA;import com.umeng.socialize.media.UMImage;import org.json.JSONException;import org.json.JSONObject;import butterknife.ButterKnife;public abstract class CanbackWebActivity extends Activity { protected WebView webview; protected NumberProgressBar progressbar; protected TextView textViewClose; protected MWebviewClient mWebviewClient; private String webTitle; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); if (null != webview && null != progressbar && null != textViewClose) { iniWebview(); initEnd(); } } @Override public Intent getIntent() { return super.getIntent(); } private void initView() { setContentView(getContentView()); ButterKnife.inject(this); webview = getWebview(); progressbar = getProgressbar(); textViewClose = getTextViewClose(); toastRoot = getLayoutInflater().inflate(R.layout.activity_sign, null); } protected abstract int getContentView(); protected abstract WebView getWebview(); protected abstract NumberProgressBar getProgressbar(); protected abstract TextView getTextViewClose(); protected abstract void setTitle(String urlTitle); protected abstract void onLoadError(WebView webView, int errorCode, String description, String failingUrl); protected abstract void onLoadEnd(String url); protected abstract void initEnd(); protected abstract void jsCallJava(MWebviewClient mWebviewClient); protected abstract void onJsRequest(Object data); private static final String APP_CACAHE_DIRNAME = "/webcache"; @SuppressLint("SetJavaScriptEnabled") @SuppressWarnings("deprecation") private void iniWebview() { 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(new MChormeClient()); mWebviewClient = new MWebviewClient(webview); webview.setWebViewClient(mWebviewClient); progressbar.setProgressTextColor(Color.parseColor("#29b6f6")); textViewClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); // 添加js交互接口类,并起别名 webtest webview.addJavascriptInterface(this, "webtest"); webview.setWebViewClient(new MWebviewClient(webview)); } protected class MWebviewClient extends WVJBWebViewClient { public MWebviewClient(WebView webView) { //交互 super(webView, new WVJBHandler() { @Override public void request(Object data, WVJBResponseCallback callback) { JSONObject outdata = (JSONObject) data; onJsRequest(outdata); Intent intent = new Intent(); 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); } } } else if } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); jsCallJava(this); } //加载开始 @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } //加载完成 @Override public void onPageFinished(WebView view, String url) { progressbar.setVisibility(View.GONE); onLoadEnd(url); super.onPageFinished(view, url); boolean isBack = 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 //动态注入js // 这段js函数的功能就是,遍历所有的img几点,并添加onclick函数,函数的功能是在图片点击的时候调用本地java接口并传递url过去 view.loadUrl("javascript:(function(){" + "var objs = document.getElementsByTagName(/"img/"); " + "for(var i=0;i<objs.length;i++) " + "{" + " objs[i].onclick=function() " + " { " + " webtest.jsInvokeJava(this.src); " + " } " + "}" + "})()"); } //加载失败 @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { progressbar.setVisibility(View.GONE); onLoadError(webView, errorCode, description, failingUrl); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { super.onReceivedSslError(view, handler, error); progressbar.setVisibility(View.GONE); } } @JavascriptInterface public void jsInvokeJava(String img) { Log.i("ddddddddddsss", "被点击的图片地址为:" + img); } protected class MChormeClient extends WebChromeClient { @Override public void onProgressChanged(WebView view, int newProgress) { 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 public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); webTitle = title; setTitle(title); } } @Override public void onBackPressed() { if (null != webview && webview.canGoBack()) { webview.goBack(); } else { webview.loadUrl("about:blank"); super.onBackPressed(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { webview.loadUrl("about:blank"); //webView.destroy(); onBackPressed(); return true; } return super.onKeyDown(keyCode, event); } private void setShareContent(String share_text, String share_image, String share_url, String title) { final SHARE_MEDIA[] displaylist = new SHARE_MEDIA[]{ SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE }; UMImage localImage = new UMImage(thisActivity, R.drawable.ic_launcher); new ShareAction(this).setDisplayList(displaylist) .withText(share_text) // 摘要 .withTitle(title) // 标题 .withTargetUrl(share_url) // 分享的网址 .withMedia(localImage) // 分享的图片 .setListenerList(new UMShareListener() { @Override public void onResult(SHARE_MEDIA platform) { T.showShort(thisActivity,"分享成功啦"); } @Override public void onError(SHARE_MEDIA platform, Throwable t) { T.showShort(thisActivity,"分享失败啦"); } @Override public void onCancel(SHARE_MEDIA platform) { T.showShort(thisActivity,"分享取消了"); } }) .open(); } private View toastRoot; private Toast toast = null; private void showToast(String msg) { TextView tv = (TextView) toastRoot.findViewById(R.id.TextViewInfo); if (toast == null) { toast = new Toast(CanbackWebActivity.this); tv.setText(msg); } else { tv.setText(msg); } toast.setView(toastRoot); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); }}剩下就是布局文件里的webview了,这个就不提供了,以上仅供参考,因为所在项目的不同,部分可能需要自行改改。
新闻热点
疑难解答