混合开发有三个步骤:
1、编写html5界面代码
2、android使用WebView
3、使用WebView特性,完成交互
下面有完整代码
第一个是html5的代码
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<title>我是测试的html页面的标题</title>
</head>
<body>
这是html页面</br>
<button onclick="s()">点击调用本地方法</button>
<a href="file:///android_asset/test.html">点击跳转到原生界面</a>
<p id="p"></p>
<script type="text/javascript">
function sum(a,b){
return a+b;
}
function alertMessage(message){
alert(message);
}
function show(){
document.getElementById("p").innerHTML="hello,damo";
}
function s(){
var result=window.android.back();
document.getElementById("p").innerHTML=result;
}
</script>
</body>
其次是android 的布局文件xml代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="50dp">
<WebView
android:id="@+id/web_view_test_web"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="点击调用JS中的方法!" />
然后是android Activity的代码
package com.dhc.jstestdemo;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
/**
* Created by 大漠dreamer on 2018/10/9.
*/
public class TestWebActivity extends Activity {
private WebView testWeb;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_web);
initView();
initData();
}
/**
* 初始化数据
*/
private void initData() {
WebSettings webSettings = testWeb.getSettings();
webSettings.setJavaScriptEnabled(true);
//window.别名.方法名,这里的别名就是android
testWeb.addJavascriptInterface(new jsInteraction(), "android");
testWeb.setWebViewClient(new WebViewClient());
testWeb.setWebChromeClient(new WebChromeClient());
}
/**
* 初始化VIEW
*/
private void initView() {
testWeb = findViewById(R.id.web_view_test_web);
testWeb.loadUrl("file:///android_asset/test.html");
}
public class jsInteraction {
@JavascriptInterface
public String back() {
return "我是JAVA中的back方法,大家好!";
}
}
public void click(View view) {
testWeb.loadUrl("javascript:alertMessage('js大哥,你猜我来自哪里呢')");
String content = "我是来自android的大猪蹄子!,请给我加转义符!";
//如果传入变量名,则需要进行转义
testWeb.loadUrl("javascript:alertMessage(\"" + content + "\")");
testWeb.evaluateJavascript("sum(5,20)", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
Toast.makeText(TestWebActivity.this, "JS返回了结果,你们看看! :" + value, Toast.LENGTH_SHORT).show();
}
});
}
}