Java 如何以编程方式关闭 Android 中的对话框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18136342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to close a Dialog in Android programmatically?
提问by Amir Hossein Ghasemi
How do I close a Dialog in android programmatically for example by a button?
如何以编程方式关闭 android 中的对话框,例如通过按钮?
Imagine I have a Dialog with a OK button on it, and want to close it by OK button, but I cant do that!
想象一下,我有一个带有 OK 按钮的对话框,想通过 OK 按钮关闭它,但我不能这样做!
I googled and found nothing useful, and almost all of them for closing AlertDialog not a Dialog.
我用谷歌搜索并没有发现任何有用的东西,几乎所有这些都是为了关闭 AlertDialog 而不是 Dialog。
回答by Philipp Jahoda
This is an example of how to create a AlertDialog with 2 Buttons (OK and cancel). When clicking the cancel button,
这是如何创建带有 2 个按钮(确定和取消)的 AlertDialog 的示例。单击取消按钮时,
dialog.dismiss()
dialog.dismiss()
is called to close the dialog.
被调用以关闭对话框。
From anywhere outside, you could call
从外面的任何地方,你都可以打电话
builder.dismiss();
builder.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Some message.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do something
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.show();
回答by Helmisek
dialog.dismiss();
Only this line will close it. :-)
只有这一行将关闭它。:-)
Implement it in the onClickListener.
在 onClickListener 中实现它。
回答by amatellanes
You can use the methods cancel()or dismiss(). The method cancel()essentially the same as calling dismiss(), but it will also call your DialogInterface.OnCancelListener(if registered).
您可以使用 方法cancel()或dismiss()。该方法cancel()本质上与调用dismiss() 相同,但它也会调用您的DialogInterface.OnCancelListener(如果已注册)。
回答by Serj Ardovic
Alternative to the dismiss();option, if you have your dialog as a separate Activity(s.a. DialogActivity), another way to close it is to call:
作为该dismiss();选项的替代方案,如果您将对话框作为单独的Activity(sa DialogActivity),另一种关闭它的方法是调用:
finish();
Call this method inside the OnClickListenerclass' onClick()method.
在OnClickListener类的onClick()方法中调用此方法。
This will call the onPause(), onStop()and onDestroy()methods consequently and kill the current activity - same as Backbutton.
这将因此调用onPause(),onStop()和onDestroy()方法并终止当前活动 - 与后退按钮相同。

