简单的实现 Js和java交互

时间:2023-02-10 14:46:59

效果:点击img标签实现图片的交替显示,实现需要懂点js,哈哈。

//上代码

public class MainActivity extends AppCompatActivity {

WebView mWebView;
android.os.Handler mHandler;

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

mWebView = (WebView)findViewById(R.id.webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
mWebView.setWebChromeClient(new MyWebChromeClient());
//"demo"是DemoJavaScriptInterface的别名,可以任意取,这是js调用java的固定格式
mWebView.addJavascriptInterface(new DemoJavaScriptInterface(),"demo");
mWebView.loadUrl("file:///android_asset/test.html");
mHandler = new android.os.Handler();
}

final class MyWebChromeClient extends WebChromeClient {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
result.confirm();
return true;
}
}

final class DemoJavaScriptInterface {

DemoJavaScriptInterface() {

}

@JavascriptInterface
public void clickOnAndroid() {
mHandler.post(new Runnable() {
public void run() {
//调用js中wave方法;("javascript:"+js方法)固定写法
mWebView.loadUrl("javascript:wave()");
}
});
}
}
}

//test.html文件内容

<html>
<script language="javascript">

var flag = false;
function wave() {
if(!flag){
flag = true;
document.getElementById("droid").src="testb.png";
}else{
flag = false;
document.getElementById("droid").src="testa.png";
}
}

</script>
<body>

<!-- window为固定写法,demo为DemoJavaScriptInterface的别名,clickOnAndroid为DemoJavaScriptInterface的方法-->
<a onClick="window.demo.clickOnAndroid()">
<div style="width:160px;
margin:0px auto;
padding:10px;
text-align:center;
border:2px solid #202020;">
<img id="droid" src="testa.png"/><br>
Click me!
</div>
</a>

</body>
</html>


//资源路径

简单的实现 Js和java交互