如何添加带有“确定”的消息框按钮?
我想显示一个带有“确定”按钮的消息框。我使用了以下代码,但它会导致带有参数的编译错误:
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("This is an alert with no consequence");
dlgAlert.setTitle("App Title");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
How should I go about displayed a message box in Android?
I want to display a message box with an OK button. I used the following code but it results in a compile error with argument:
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("This is an alert with no consequence");
dlgAlert.setTitle("App Title");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
How should I go about displaying a message box in Android?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为可能存在问题,您没有为“确定”按钮添加点击侦听器。
I think there may be problem that you haven't added click listener for ok positive button.
由于在您的情况下,您只想通过简短的消息通知用户,因此
Toast
将带来更好的用户体验。如果您想要给读者时间阅读和理解较长的消息,那么您应该使用
DialogFragment
。 (文档目前建议包装您的AlertDialog
在片段中而不是直接调用它。)创建一个扩展
DialogFragment
的类:然后在您的活动中需要它时调用它:
另请参阅
< a href="https://i.sstatic.net/PBqE4.png" rel="noreferrer">
Since in your situation you only want to notify the user with a short and simple message, a
Toast
would make for a better user experience.If you have a more lengthy message that you want to give the reader time to read and understand, then you should use a
DialogFragment
. (The documentation currently recommends wrapping yourAlertDialog
in a fragment rather than calling it directly.)Make a class that extends
DialogFragment
:Then call it when you need it in your activity:
See also
该代码对我来说编译正常。可能您忘记添加导入:
无论如何,您有一个很好的教程 在这里。
The code compiles ok for me. May be you have forgotten to add the import:
Anyway, you have a good tutorial here.