你好,我尝试了几天的几种方法来使它正常工作,但我失败了,如果有人能帮我找出我做错了什么,我想要的只是当我按下按钮时它会显示 javascript Toast 中的文本:
我的 java 主程序:
package com.callphone;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String content = "file:///android_asset/www/mypage.html";
WebView webView = (WebView) findViewById(R.id.mybrowser);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl(content);
webView.addJavascriptInterface(new MyJavaScriptInterface(this), "AndroidFunction");
}
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
public void showToast(String toast){
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
}
我的 xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView
android:id="@+id/mybrowser"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
我的 html:
<!DOCTYPE html>
<html>
<head>
<script src="index.js"></script>
</head>
<body>
<h1>What's your number</h1>
<button onclick="shownumber('55555')">show number</button>
</body>
</html>
和我的javascript:
函数显示数字(数字){
AndroidFunction.showToast(数字);
}
当我更改 javascript 以提醒它显示提醒时,所以我发现了 AndroidFunction 的问题
提前致谢。
最佳答案
根据doucmentation您在 MyJavaScriptInterface
这应该有效:
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void showToast(String toast){
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
关于java - eclipse 使用 JavascriptInterface 从 javascript 触发 toast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17945556/