原生Android可以嵌入webView,webView,native,weex三者之间可以交互,主要通过native这个桥梁
一般有以下几种情况:
- webView–>native
- webView–>weex
- native–>webView
- weex–>webView
其实以上无论是如何跳转,我们所要做的就是将webView的js文件和Android(native)交互起来
首先在Android方面,创建webViewActivity.
activity_webView
<WebView
android:id="@+id/wv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints">
</WebView>
public WebView wv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webView);
HashMap<String, String> header = new HashMap<>();
header.put("token", "");
wv.loadUrl(getIntent().getStringExtra("url"),header);
//设置方法名
wv.addJavascriptInterface(this,"nativeMethod");
}
@JavascriptInterface
public void openPage(String url) throws UnsupportedEncodingException {
//webView传递过来做的一些操作
}
其次在js文件方面
<a href="javascript:;" onclick="openPage(id)">跳转原生/weex</a>
function openPage(id) {
var weexUrl = encodeURIComponent(url);
var param = encodeURIComponent(JSON.stringify({id:id}));
var url = `page://weex?url=${weexUrl}¶m=${param}`;
//关键点
nativeMethod.openPage(url);
}
从上面我们可以看到,当我们从原生点击跳到webViewActivity时,会加载webView的url,当我们点击webview页面中的openPage时,我们就可以跳回到webViewActivity的openPage方法内,然后在其中我们可以做一些操作,比如跳转到weex页面或者是其他的原生页面。
撒花完结~