【问题标题】:How to return Android's Alert return value to WebView with JavascriptInterface?如何使用JavascriptInterface将Android的Alert返回值返回给WebView?
【发布时间】:2018-06-07 10:53:56
【问题描述】:

我为我的浏览器游戏创建了一个 Android WebView 应用程序。我使用 Javascript-Alert 询问用户是否真的想重置分数。但我想使用 Android Alert 而不是 Javascript Alert。所以我创建了一个 Javascript 接口。

public class AlertJSInterface {
private Context context;

AlertJSInterface(Context c) {
    context = c;
}

@JavascriptInterface
public boolean alert(String title, String message) {
    AlertDialog.Builder alert = new AlertDialog.Builder(context);
    alert.setTitle(title);
    alert.setMessage(message);
    alert.setCancelable(true);
    alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });
    alert.show();

    //want to return true if clicked ok
}

现在我需要 Javascript 中的 Android Alert 的返回值。问题是 Android Alert 有一个 ClickListener。但是我怎样才能将值返回给 Javascript?

if(AndroidAlert.alert(resetScoreTitle, resetScoreAck) === true) {
    resetAll();
}

【问题讨论】:

    标签: javascript android webview interface alert


    【解决方案1】:

    如果在用户单击“确定”按钮后调用 js 函数怎么办。就像:

    alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
           myWebView.loadUrl("javascript:resetAll();");
        }
    });
    

    【讨论】:

    • 我怎样才能访问网页视图?我的 Webview 在 MainActivity 中被清除。
    • err,,setter 和 getter?用构造函数传递它?让它静态?你喜欢的任何东西
    • 我尝试使用静态和构造函数...java.lang.RuntimeException: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 2) {80fa4a0} called on Looper (JavaBridge, tid 351) {1f7547f}, FYI main Looper is Looper (main, tid 2) {80fa4a0})
    • 好的,我用this thread解决了我的异常
    猜你喜欢
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多