如何在android中使用javascript界面以及如何在android对话框中显示结果

how to use javascript interface in android and how to display the result in android dialog box

本文关键字:android 对话框 显示 结果 javascript 界面      更新时间:2023-09-26

请解释清楚,因为我是新的javascript和android *

如何在Java脚本中创建两个随机数的加减运算(使用javascript接口),点击加减按钮(按钮逻辑必须在android中编写)结果必须在android警报或对话框中显示

//在主活动中使用javascript接口////

使用android按钮我们需要在android对话框中显示结果

请解释清楚,因为我是新的javascript和android*

1)首先,在android中编写一个类,这个类将通过javascript调用:

public class JavaScriptCallFunc {
    Context mContext;
    JavaScriptCallFunc(Context c) {
        mContext = c;
    }
    public void showToastMsg(String s) {
        //do something
        Toast.makeText(mContext, s, Toast.LENGTH_LONG).show();
    }
}
2)addJavascriptInterface for webview in activity
    mWebView = (WebView)findViewById(R.id.webView);
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(new JavaScriptCallFunc(this), "Android");

3)调用Java函数

function callAndroidShowToast(msg) {
    Android.showToastMsg(msg);

}