How can I call a dialog from a webview?

為{幸葍}努か 提交于 2021-01-28 05:26:27

问题


I have a webview and a class with functions that will be used with javascript inside the webview

class with functions (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?

I've tried to call like:

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

but it doesn't do nothing


回答1:


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:

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



来源:https://stackoverflow.com/questions/59632372/how-can-i-call-a-dialog-from-a-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!