android 與JavaScript中怎么實現互相調用,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
1.html代碼
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<title>Android/Javascript互調Demo</title>
<script type="text/javascript" language="javascript">
function callJavaScriptMethod()
{
document.getElementById("content").innerHTML = "Android 調用 Javascript 成功";
}
</script>
</head>
<body>
<div ><a onClick="window.demo.callJavaMethod()" href="">點擊-->JS調用Android代碼</a></div>
<div id="content"></div>
</body>
</html>2.xml布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/androidCallJSBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="點擊 Android 調用 JavaScript"/> </LinearLayout>
3.Activity測試代碼
package com.testwebview;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private WebView mWebView;
private Button androidCallJSBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
private void initView() {
mWebView = (WebView) findViewById(R.id.webview);
WebSettings mWebSettings = mWebView.getSettings();
mWebSettings.setJavaScriptEnabled(true); //加上這句話才能使用javascript方法
mWebView.addJavascriptInterface(new Object() {//增加接口方法,讓html頁面調用
public void callJavaMethod() {
Toast.makeText(getApplicationContext(), "JS調用Android成功", Toast.LENGTH_LONG).show();
}
}, "demo");
mWebView.loadUrl("file:///android_asset/demo.html"); //加載頁面
androidCallJSBtn = (Button) findViewById(R.id.androidCallJSBtn);
androidCallJSBtn.setOnClickListener(new Button.OnClickListener() { //給button添加事件響應,執行JavaScript的fillContent()方法
public void onClick(View v) {
mWebView.loadUrl("javascript:callJavaScriptMethod()");
}
});
}
}
4.效果圖(依次是未調用前、android調用JS、JS調用android)
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。