简体   繁体   English

如何从 webview 调用对话框?

[英]How can I call a dialog from a webview?

I have a webview and a class with functions that will be used with javascript inside the webview我有一个 webview 和一个函数类,这些函数将在 webview 中与 javascript 一起使用

class with functions (WebAppInterface.java):带函数的类(WebAppInterface.java):

public class WebAppInterface {
    Context mContext;

    WebAppInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public void closeApp() {
        ((Activity)mContext).finishAffinity();
    }

    @JavascriptInterface
    public void refresh() {
        Intent i = new Intent(mContext, MainActivity.class);
        mContext.startActivity(i);
        ((Activity)mContext).finish();
    }
}

How can I call/create a Dialog class inside this file?如何在此文件中调用/创建 Dialog 类?

I've tried to call like:我试过这样称呼:

Dialog ex = new Dialog();
ex.show(getSupportFragmentManager(), "Dialog");

but it doesn't do nothing但它什么也不做

I hope you have added in your activity:我希望你在你的活动中添加了:

WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");

WebAppInterface should not extend Activity: WebAppInterface 不应扩展 Activity:

public class WebAppInterface {
Context mContext;

/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
    mContext = c;
}

/** Show a toast from the web page */
@JavascriptInterface
public void showDialog(String text) {
    //here code of alert dialog 
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    builder.setTitle("abcd");
    builder.setMessage(text);
    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    Dialog dialog = builder.create();
    dialog.show();
}}

Now you have activity context in class so you can perform all other task in this class现在您在课堂上有了活动上下文,因此您可以在这个课堂上执行所有其他任务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM