Android之WebView的使用

android一大神器==webview,在2016年到2017年期间就是因为它的存在,才会对整个IT安卓行业都造成了很大的冲击,

webview它只是一个控件,使用它可以直接加载h5的页面,这样也就避免了一些屏幕适配什么的,当然使用它可还不仅仅这一点好处,还有,比如:

1.跨平台,网页代码你写一次,Android运行,IOS也可以云

2.节省成本

3.开发效率提高

4.应用程序维护成本大大降低,只用维护服务器端的代码,比如你原生的写,你想把一个控件删掉,手续很麻烦,h5删一个控件,服务器上删掉,就大功告成

正所谓,有利就有弊,它的弊端,也就是最致命的地方在于:

运行效率差,消耗手机的流量,性能透支更加严重,无法完成酷炫的效果

所以,这也是现在市场有摒弃它的原因,但我们作为资深程序员,我们还是要了解他的,下面就一起来研究吧,效果就是上面的动图,代码如下:

有兴趣的还可以下载我的Demo:下载Demo

首先是布局,包含进度条的:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" tools:context="bw.com.webviewlianxi.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/weburl"
            android:singleLine="true"
            android:layout_width="0dp"
            android:layout_weight="9"
            android:layout_height="wrap_content"
            />
        <Button
            android:id="@+id/go"
            android:layout_width="20dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="GO"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/wucan"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="使用无参,调js函数,向js页面动态添加元素"/>
        <Button
            android:id="@+id/youcan"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="使用有参,调js函数,向js页面动态添加元素"/>
    </LinearLayout>

    <ProgressBar
        android:visibility="invisible"
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView"></WebView>
</LinearLayout>
接着就是Activity的逻辑代码:

package bw.com.webviewlianxi;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText weburl;
    private Button go;
    private WebView webView;
    private ProgressBar progressBar;
    private Button wucan;
    private Button youcan;
    //"file:///android_asset/test.html"

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 下方2行代码是指在当前的webview中跳转到新的url
                view.loadUrl(url);
                return true;
            }
        });//不去跳转到别的浏览器

        WebSettings settings = webView.getSettings();//获得设置页面的权限

        settings.setJavaScriptCanOpenWindowsAutomatically(true);//设置javascript弹窗

        settings.setJavaScriptEnabled(true);//是安卓支持js脚本

        settings.setSupportZoom(true);//支持缩放网页

        webView.setWebChromeClient(new WebChromeClient());//使安卓支持网页的弹出框

        // 设置JavascriptInterface
        // javainterface实际就是一个普通的java类,里面是我们本地实现的java代码
        // object 传递给webview,并指定别名,这样js脚本就可以通过我们给的这个别名来调用我们的方法
        // 在代码中,TestInterface是实例化的对象,testInterface是这个对象在js中的别名
        webView.addJavascriptInterface(new TestInterface(), "testInterface");

        //加载进度条
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    progressBar.setVisibility(View.INVISIBLE);
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                }
            }
        });

    }
    
    //快捷键生成  获取id
    private void initView() {
        weburl = (EditText) findViewById(R.id.weburl);
        go = (Button) findViewById(R.id.go);
        webView = (WebView) findViewById(R.id.webView);

        go.setOnClickListener(this);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        wucan = (Button) findViewById(R.id.wucan);
        wucan.setOnClickListener(this);
        youcan = (Button) findViewById(R.id.youcan);
        youcan.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.go:
                submit();
                break;
            case R.id.wucan:
                webView.loadUrl("javascript:javacalljs()");
                break;
            case R.id.youcan:
                String content = "超级帅!";
                webView.loadUrl("javascript:javacalljswithargs('" + content + "')");
                break;
        }
    }

    //获取输入框中的值
    private void submit() {
        // validate
        String weburlString = weburl.getText().toString().trim();
        if (TextUtils.isEmpty(weburlString)) {
            Toast.makeText(this, "weburlString不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        //http://m.mv14449315.icoc.bz/index.jsp
        // TODO validate success, do something
        Log.i("jiba", "===" + weburlString);
        webView.loadUrl(weburlString);//加载本地路径文件,,url
    }

    /**
     * Js调用的JavascriptInterface
     */
    public class TestInterface {

        /**
         * 因为安全问题,在Android4.2以后(如果应用的android:targetSdkVersion数值为17+)
         * JS只能访问带有 @JavascriptInterface注解的Java函数。
         */
        @JavascriptInterface
        public void startCall() {
//            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + 10086));
//            startActivity(intent);
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("是否确认拨打电话?");
            builder.setPositiveButton("确认", null);
            builder.setNegativeButton("取消", null);
            builder.show();
        }

        @JavascriptInterface
        public void showToast(String content) {
            Toast.makeText(MainActivity.this, "js调用了java函数并传递了参数:" + content, Toast.LENGTH_SHORT).show();
        }
    }
}
最后,在附上一章自己写的h5页面,有点low:

<html>  
   <head>  
      <meta http-equiv="Content-Type"  content="text/html;charset=utf-8">
      <script type="text/javascript">  
            function javacalljs(){  
                document.getElementById("content").innerHTML +=
                   "<br\>java调用了js函数";
            }  
              
            function javacalljswithargs(arg){  
                document.getElementById("content").innerHTML +=     
                   ("<br\>"+arg);  
            }  
              
      </script>  
   </head> 

   <body>  
         这是一个HTML页面,页面有如下2个功能 <br/> 
         <br/>
         <br/>
         <!--点击该标签,通过别名来识别android的对象,并调用其对象的方法-->
         <a onClick="window.testInterface.startCall()">点击拨打10086</a><br/>
         <a onClick="window.testInterface.showToast('我弹了一个Toast')" >点击弹出Toast,内容为我弹了一个Toast”</a>
         <br/>
         <br/>
         <br/>
         <br/>
         <div id="content">HTML内容显示区:</div>  
   </body>  
</html


猜你喜欢

转载自blog.csdn.net/weixin_40430041/article/details/79204377