Android与JS互调,Android与JS相互传值,webview展现

源码下载:javascript

https://download.csdn.net/download/qq_31939617/10380516 下载php

1.本文采用的是android调用assest中的本地.html文件,webview展现(加载网络的html效果是同样的,把url替换掉就行)
2.包含本地.html文件加载,点击.html控件,Android端响应
3.包含本地.html文件加载,点击.html控件,传值到Android端
4.包含本地.html文件加载,Android端传值到到htmlcss

先看目录结构
这里写图片描述html

DetailsActivity.classjava

package com.example.sz.androidandjstest;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.example.sz.androidandjstest.CustomProgressDialog;

public class DetailsActivity extends AppCompatActivity {
    private static final String TAG = "DetailsActivity";
    private WebView mWebView;
    String url;

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


        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        final CustomProgressDialog dialog = new CustomProgressDialog(this);

        Intent intent = getIntent();
        url = intent.getStringExtra("url");

        mWebView = (WebView) findViewById(R.id.webview);

        WebSettings setting = mWebView.getSettings();
        setting.setJavaScriptEnabled(true);//让webview支持javascript
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//设置容许js弹出alert对话框
        setting.setDefaultTextEncodingName("utf-8");//设置字符集
        //setting.setBlockNetworkImage(true);//设置不能访问网络图片

        // setting.setSupportZoom(true);//开启网页的缩放
        // setting.setBuiltInZoomControls(true);

        setting.setLoadWithOverviewMode(true);//设置网页缩放至手机大小
        setting.setUseWideViewPort(true);

        mWebView.getSettings().setJavaScriptEnabled(true);//让webview支持javascript
        mWebView.setWebChromeClient(new WebChromeClient());//支持特殊javascript


        // mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        // mWebView.setBackgroundColor(Color.parseColor("#000000"));


        //load本地
        // mWebView.loadUrl("file:///android_asset/hellotest.html");
        //mWebView.loadUrl("file:///android_asset/feedback(1).html");
        mWebView.loadUrl("file:///android_asset/feedback.html");
        //load在线
        //mWebView.loadUrl("http://www.google.com");

        // mWebView.loadUrl(url);


        //js访问android,定义接口
        mWebView.addJavascriptInterface(new JsInteration(), "control");

        //设置了Alert才会弹出,从新onJsAlert()方法return true能够自定义处理信息
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                //return super.onJsAlert(view, url, message, result);
                Toast.makeText(DetailsActivity.this, message, Toast.LENGTH_LONG).show();
                return true;
            }
        });


        //全部的请求在本地webview打开
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
                // view.loadUrl(url);
                //return true;
                //请求链接
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                //开始加载链接
                // dialog.show();
                showProgressLayer("", "正在努力加载中……");


            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                //mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); //禁止硬件加速
                //加载结束
                // dialog.dismiss();
                mProgressDialog.dismiss();

            }



        });

        mWebView.loadUrl(url);

    }




    ProgressDialog mProgressDialog;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //返回键
            if (mWebView.canGoBack()) {
                //返回键webView
                mWebView.goBack();
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }


    public void showProgressLayer(String tipTitle, String tipContent) {

        try {
            closeProgressLayer();
            this.mProgressDialog = new ProgressDialog(this);
            this.mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            if (tipTitle != null)
                if (tipContent != null)
                    this.mProgressDialog.setMessage(tipContent);
            this.mProgressDialog.setIndeterminate(true);
            this.mProgressDialog.setCancelable(true);
            this.mProgressDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void closeProgressLayer() {
        try {
            if (this.mProgressDialog == null)
                return;
            this.mProgressDialog.cancel();
            this.mProgressDialog = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /** * js调用android的方法 */
    class JsInteration {
        @JavascriptInterface
        public void toastMessage(String message) {
            //Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
            Toast.makeText(getApplicationContext(), "评价成功", Toast.LENGTH_LONG).show();
           // startActivity(new Intent(DetailsActivity.this, MainActivity.class));
        }

        @JavascriptInterface
        public void onSumResult(int result) {
            Toast.makeText(getApplicationContext(), "我是android调用js方法(4.4前),入参是1和2,js返回结果是" + result, Toast.LENGTH_LONG).show();
        }
    }
}

activity_details.xmljquery

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
    <WebView  android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent" />

   <!-- android:scrollbars="none" android:layerType="software"-->

</LinearLayout>

laod_progressbar_layout.xmlandroid

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/transparent">

    <ProgressBar  android:id="@+id/progress_progress" style="@style/progress_dialog_loading" android:layout_width="48dp" android:layout_height="48dp" android:layout_centerInParent="true" android:indeterminateDrawable="@drawable/progressbar_load" android:padding="1dp" android:visibility="visible" />

    <TextView  android:id="@+id/progress_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/progress_progress" android:layout_centerHorizontal="true" android:layout_marginTop="30dp" android:text="正在努力加载中……" android:textColor="@color/colorPrimaryDark" android:textSize="16sp" android:visibility="visible" />
</RelativeLayout>

CustomProgressDialog.classweb

package com.example.sz.androidandjstest;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;

public class CustomProgressDialog extends ProgressDialog {
    private String message = "";

    public CustomProgressDialog(Context context, int theme) {
        super(context, theme);
    }

    public CustomProgressDialog(Context context) {
        super(context);
    }

    public CustomProgressDialog(Context context, int theme,
                                String message) {
        super(context, theme);
        this.message = message;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.laod_progressbar_layout);
        //dialog弹出后点击物理返回键Dialog消失,可是点击屏幕不会消失
        this.setCanceledOnTouchOutside(false);

        //dialog弹出后点击屏幕或物理返回键,dialog都不消失
        //this.setCancelable(false);
      if (message != null){
           // ((TextView)findViewById(R.id.progress_text)).setText(message);
            ((TextView)findViewById(R.id.progress_text)).setText("正在努力加载中……");
        }
    }
}

progressbar_load.xmlajax

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android" android:fromDegrees="0" android:pivotX="50%" android:pivotY="50%" android:toDegrees="360">

    <!-- 这里画了一个灰色的环形 -->
    <shape  android:innerRadiusRatio="3" android:shape="ring" android:thicknessRatio="8" android:useLevel="false">
        <!-- 径向渐变 -->
        <gradient  android:centerColor="#c8e9f9" android:centerX="1.0" android:centerY="1.0" android:endColor="#5ea9ff" android:gradientRadius="90" android:startColor="#01026b" android:type="radial" android:useLevel="false" />
    </shape>

</rotate>

ic_launcher_background.xml网络

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportHeight="108" android:viewportWidth="108">
    <path  android:fillColor="#26A69A" android:pathData="M0,0h108v108h-108z" />
    <path  android:fillColor="#00000000" android:pathData="M9,0L9,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M19,0L19,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M29,0L29,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M39,0L39,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M49,0L49,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M59,0L59,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M69,0L69,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M79,0L79,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M89,0L89,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M99,0L99,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M0,9L108,9" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M0,19L108,19" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M0,29L108,29" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M0,39L108,39" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M0,49L108,49" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M0,59L108,59" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M0,69L108,69" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M0,79L108,79" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M0,89L108,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M0,99L108,99" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M19,29L89,29" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M19,39L89,39" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M19,49L89,49" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M19,59L89,59" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M19,69L89,69" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M19,79L89,79" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M29,19L29,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M39,19L39,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M49,19L49,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M59,19L59,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M69,19L69,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path  android:fillColor="#00000000" android:pathData="M79,19L79,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
</vector>

feedback.html

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <title></title> <link href="../css/mui.min.css" rel="stylesheet" /> <link rel="stylesheet" href="../css/reset.css" /> <script type="text/javascript" src="../js/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="../js/public.js"></script> <script type="text/javascript" src="../js/mui.js"></script> </head> <style type="text/css"> /*body { margin: 0px; padding: 0px; } */ .container { width: 100%; height: 100%; background: url("../image/84.png") no-repeat; margin: 0rem; padding-top: 0.6rem; } .service { height: 0.3rem; font-family: PingFang-SC; font-size: 0.42rem; font-weight: 300; letter-spacing: 0.007rem; text-align: center; color: #fff; position: relative; } .service:after { position: absolute; content: ""; bottom: -30px; width: 10%; left: 45%; background: yellow; height: 3px; } .star { display: flex; flex-direction: row; width: calc(100% - 1.2rem); margin: 0rem auto; padding-top: 1.8rem; } .star p { width: 20%; text-align: center; } .star p img { width: 1.2rem; height: 1.2rem; } .active { color: #fff; background-image: linear-gradient(to top, #7440ca, #5781eb); } .left { width: 90%; height: 0.71rem; display: flex; flex-direction: row; margin: 0rem auto; margin-top: 1.5rem; justify-content: center; line-height: 3.43; flex-flow: wrap; } .right { width: 90%; height: 0.71rem; display: flex; flex-direction: row; margin: 0rem auto; margin-top: 1rem; justify-content: center; line-height: 3.43; } .right-one { width: 45%; height: 0.71rem; margin-right: 5%; border-radius: 0.07rem; border-style: solid; border-width: 0.01rem; border-image-slice: 1; font-size: 0.42rem; font-weight: 100; color: yellow; text-align: center; line-height: 1.42rem width: 45%; height: 1.42rem; } .left-two, .right-two { width: 45%; height: 0.71rem; margin-right: 5%; border-radius: 0.07rem; border: 0.02rem solid yellow; border-image-slice: 1; font-size: 0.42rem; font-weight: 100; color: yellow; text-align: center; line-height: 1.42rem width: 45%; height: 1.42rem; margin-bottom: 0.3rem; } .submit { width: 80%; height: 1.32rem; margin-left: 10%; border-radius: 0.07rem; background-image: linear-gradient(to right, #7440ca, #257cfe); margin-top: 6rem; font-size: 0.42rem; font-weight: 100; line-height: 3.43; letter-spacing: 0.007rem; color: #fff; text-align: center; } </style> <body style="overflow: hidden;"> <script> function toastMessage(abc) { window.control.toastMessage(abc); } </script> <div class="container"> <div class="service">服务评价</div> <div class="outline"></div> <div class="star"> <p><img src="../image/2-4.png" </p> <p><img src="../image/2-4.png" </p> <p><img src="../image/2-4.png" </p> <p><img src="../image/2-4.png" </p> <p><img src="../image/2-4.png" </p> </div> <div class="left"> <div class="right-one left-two statu ">服务态度好</div> <div class="left-two statu">总体流程体验好</div> <div class="left-two statu">实用有价值</div> <div class="right-two left-two statu">界面好看</div> </div> <!--<div class="right"> <div class="left-two statu">实用有价值</div> <div class="right-two left-two statu">界面好看</div> </div>--> <div class="submit" onclick="toastMessage('123')"> 提交评价 </div> </div> </body> <script type="text/javascript"> mui.ready(function() { pageInfo(); }); function pageInfo() { mui.ajax({ url: '/gateway.php?method=getTags', type: 'post', data: {}, success: function(data) { var data = JSON.parse(data).data; var content = ""; for(var i in data) { content += `<div class="right-one left-two statu " data-id="${data[i]['id']}">${data[i]['tagName']}</div>`; } $('.left').html(content); $('.star').find('p').click(function() { var index = $(this).index(); $('.star').find('p').each(function(i) { i <= index ? $(this).children().attr('src', '../image/2-3.png') : $(this).children().attr('src', '../image/2-4.png'); i <= index ? $(this).addClass('starActive') : $(this).removeClass('starActive'); }) }) $('.statu').click(function() { if($(this).hasClass('active')) { $(this).removeClass('active').removeClass('right-one'); } else { $(this).addClass('active').addClass('right-one'); } }) $('.submit').click(function() { var statu = []; $('.statu').each(function() { if($(this).hasClass('active')) { statu.push($(this).attr('data-id')); } }) var strtNum = 0; $('.star').find('p').each(function() { if($(this).hasClass('starActive')) { strtNum++; } }) if(strtNum> 0 && statu != "") { mui.ajax({ url: '/gateway.php?method=doComment', type: 'post', data: { star:strtNum, tags:statu.join(',') }, success: function(data) { var data = JSON.parse(data); if(data.err) { mui.toast(data.msg); }else { mui.toast('评价成功'); } } }) }else { mui.toast('请选择评价项'); } }) } }) } </script> </html>

源码下载:

https://download.csdn.net/download/qq_31939617/10380516 下载