美文网首页
万能的webView之Activity

万能的webView之Activity

作者: 易瑞 | 来源:发表于2017-08-13 18:14 被阅读0次

    对于使用webview加载一个网页,使用它的loadurl()方法即可,如果在程序内要打开网页,难么就要自己创建一个WebViewClient,通过setWebViewClient进行关联,再如果网页里面有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

    //动态注入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

    相关文章

      网友评论

          本文标题: 万能的webView之Activity

          本文链接:https://www.haomeiwen.com/subject/vkuerxtx.html