标签:java 接口 file android js 交互
在JS中调用Java方法:
(1) 首先为JS提供接口
WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = (WebView) findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); webView.loadUrl(" file:///android_asset/js/index.html "); webView.addJavascriptInterface(new AndroidToastForJs(MainActivity.this), "demo"); } public class AndroidToastForJs { private Context mContext; public AndroidToastForJs(Context context) { this.mContext = context; } @JavascriptInterface public String getTitle(){ return "This is Titl"; } @JavascriptInterface public String getContent(){ return "this is content ,this is contentthis is contentthis is content"; } @JavascriptInterface public String getStatement(){ return "this is statement"; } }
将这个接口对象传给JS( WebKit )
webView.addJavascriptInterface(new AndroidToastForJs(MainActivity.this), "demo");
于是,现在JS知道了一个叫做“demo”的接口类可以供他使用
(2)在JS中调用Java方法:
<html lang="en"> <!-- By ElyarAnwar--> <script> window.onload = function(){getTitle();getContent();getStatement()}; function getTitle() { var title = document.getElementById(‘title‘); title.innerHTML = window.demo.getTitle(); } function getContent(){ var content = document.getElementById(‘content‘); content.innerHTML = window.demo.getContent(); } function getStatement(){ var statement = document.getElementById(‘statement‘); statement.innerHTML = window.demo.getStatement(); } </script> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="bootstrap.min.css"> </head> <body> <!-- Begin page content --> <div class="container"> <div class="page-header text-center" style="font-family: SketchRockwell"> <h4><span><strong id="title"></strong></span></h4> </div> <p id="content" class="lead text-justify" style="font-family: SketchRockwell"></p> </div> <footer class="footer"> <div class="container"> <p id="statement" class="text-muted text-right" style="font-family: ‘SketchRockwell"></p> </div> </footer> </body> </html>
完成在JS中调用Java方法!
图:
本文出自 “分享是最好的记忆” 博客,谢绝转载!
Android分享笔记(5) Android 与 JS 交互
标签:java 接口 file android js 交互
原文地址:http://elyar.blog.51cto.com/9864306/1752300