问题
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