Android 我应该在什么上下文中使用 AlertDialog.Builder?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3326366/
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
what context should i use AlertDialog.Builder in?
提问by pavanred
Could anyone please explain what context should i use the AlertDialog.Builder class? I am new to android app development and I frankly don't understand which context to use when?
谁能解释一下我应该使用 AlertDialog.Builder 类的上下文吗?我是 android 应用程序开发的新手,坦率地说,我不明白什么时候使用哪个上下文?
Say, I want to create an object for AlertDialog.Builder class -
说,我想为 AlertDialog.Builder 类创建一个对象 -
AlertDialog.Builder ab = new AlertDialog.Builder();
ab.setMessage("Test");
ab.show();
What context should I use it in? Does it differ if I use the Alert Dialog onCreate
or OnClickListener
or in the handler of any such event?
我应该在什么情况下使用它?请问如果我使用的警告对话框中是不同onCreate
或OnClickListener
或在任何此类事件的处理程序?
采纳答案by Brandon O'Rourke
In the first version of my app I made the mistake of not using onCreateDialog and instead built and showed the dialogs myself. If you do it yourself you have to take care of things like dismissing the dialog before the activity is finish()ed otherwise a window will leak.
在我的应用程序的第一个版本中,我犯了一个错误,没有使用 onCreateDialog 而是自己构建和显示对话框。如果你自己做,你必须处理一些事情,比如在活动完成之前关闭对话框(),否则窗口会泄漏。
I would override onCreateDialog in your activity and return ab.create() (not show()). onCreateDialog will then handle showing the dialog and you'll just have to call showDialog(id).
我会在您的活动中覆盖 onCreateDialog 并返回 ab.create() (而不是 show())。然后 onCreateDialog 将处理显示对话框,您只需调用 showDialog(id)。
回答by Cristian
You should use the context of the Activity that it's executed from. In other words, just use YourNameOfActivity.this
as context.
您应该使用从中执行它的 Activity 的上下文。换句话说,仅用YourNameOfActivity.this
作上下文。
回答by K.Muthu
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Test")
.show;
(or) if u want (yes,no) button means use this
(或)如果你想要(是,否)按钮意味着使用这个
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener)
.show();