gpt4 book ai didi

javascript - 从 JavaScript 调用 Android 方法

转载 作者:IT老高 更新时间:2023-10-28 21:45:56 25 4
gpt4 key购买 nike

我搜索了,但没有找到答案。我正在使用 HTML5 和 JavaScript 开发基于 webview 的 Android 应用程序。我可以从 JavaScript 调用 Android 方法,例如 makeToast() 吗?

最佳答案

您可以通过将 JavaScript 接口(interface)添加到您的 WebView 并将特定方法公开给在您的 Web View 中运行的 JavaScript 代码来实现此目的。换句话说,您需要将对 Android 的 Toast 类的调用封装在您在 Activity/Fragment 中创建的方法中。

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<WebView android:id="@+id/web_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {

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

WebView webView = (WebView)findViewById(R.id.web_view);
webView.loadUrl("file:///android_asset/web.html");

webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebViewJavaScriptInterface(this), "app");
}

/*
* JavaScript Interface. Web code can access methods in here
* (as long as they have the @JavascriptInterface annotation)
*/
public class WebViewJavaScriptInterface{

private Context context;

/*
* Need a reference to the context in order to sent a post message
*/
public WebViewJavaScriptInterface(Context context){
this.context = context;
}

/*
* This method can be called from Android. @JavascriptInterface
* required after SDK version 17.
*/
@JavascriptInterface
public void makeToast(String message, boolean lengthLong){
Toast.makeText(context, message, (lengthLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT)).show();
}
}

}

Assets /web.html

<!DOCTYPE html>
<html>
<head>
<title>JavaScript View</title>

<script type="text/javascript">

function showToast(){
var message = document.getElementById("message").value;
var lengthLong = document.getElementById("length").checked;

/*
Call the 'makeToast' method in the Java code.
'app' is specified in MainActivity.java when
adding the JavaScript interface.
*/
app.makeToast(message, lengthLong);
return false;
}

/*
Call the 'showToast' method when the form gets
submitted (by pressing button or return key on keyboard).
*/
window.onload = function(){
var form = document.getElementById("form");
form.onsubmit = showToast;
}
</script>
</head>

<body>

<form id="form">
Message: <input id="message" name="message" type="text"/><br />
Long: <input id="length" name="length" type="checkbox" /><br />

<input type="submit" value="Make Toast" />
</form>

</body>
</html>

A Toast Message

关于javascript - 从 JavaScript 调用 Android 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22895140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com