android的webview交互(java,javascript)

1、先让本地html运行起来

web = (WebView) findViewById(R.id.web);
web.loadUrl("file:///android_asset/wm/detail.html");

detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>任务1</title>
    <link type="text/css" rel="stylesheet" href="index.css">
    <script type="text/javascript" src="flexible.min.js"></script>
</head>
<body>
<button  onClick="window.test.clickOnAndroid()">测试按钮</button>
<script>
 document.getElementById("h1").value="vr";
function myfun(){
                window.test.clickOnAndroid()
            };

</script>
</body>
</html>

assets文件夹位置                                                              创建assets文件夹

                                          

2、js----------->java

//打开webview对js的主持
web.getSettings().setJavaScriptEnabled(true);
//绑定js要调用的java
web.addJavascriptInterface(new MyObject(),"test");
//内部类
class MyObject extends Object {
       @JavascriptInterface
       public void clickOnAndroid() {
           Toast.makeText(webviewjiaohu.this, "js交互java", Toast.LENGTH_SHORT).show();
       }
  }

3、java---------->js

写个button监听调用一下代码

 new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        web.loadUrl("javascript:myfun()");
                    }
                });

 

©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页