安卓简单提示对话框

170

我需要向在我的Android应用上点击按钮的用户显示一条小文本消息,在IOS上,我只需创建一个很容易使用的AlertView即可,但在Android上我很苦恼,因为解决方案似乎要难十倍。我看到需要使用DialogFragment,但我无法理解如何使其工作,有人能解释一下吗?另外,我的解决方案是否正确,或者有更简单的方法向用户显示简单的文本消息?

3个回答

488

您只需要在onClick中执行此操作:

AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
alertDialog.show();

我不知道你从哪里得出需要使用 DialogFragment 来显示警报的结论。


12
FYI - 谷歌的Android开发网站上的第一个例子展示了如何使用Fragment实现这一点:http://developer.android.com/guide/topics/ui/dialogs.html。我认为这可能会让开发人员认为他需要使用Fragment来创建一个基本的AlertDialog。今天我进行了搜索,觉得可能是这样。 - raddevus
5
最好在builder上设置属性而不是在alertDialog实例上! - alexbirkett

30

不是的,我的朋友。很简单,试试用这个:

AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to dear user.");
alertDialog.setIcon(R.drawable.welcome);

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
    }
});

alertDialog.show();

这个教程展示了如何使用xml创建自定义对话框,并将它们显示为警告对话框。


你没有传递哪个按钮。 - Leon

25

你可以轻松地制作自己的“AlertView”并在任何地方使用它。

alertView("You really want this?");

只需实现一次:

private void alertView( String message ) {
 AlertDialog.Builder dialog = new AlertDialog.Builder(context);
 dialog.setTitle( "Hello" )
       .setIcon(R.drawable.ic_launcher)
       .setMessage(message)
//     .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//      public void onClick(DialogInterface dialoginterface, int i) {
//          dialoginterface.cancel();   
//          }})
      .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialoginterface, int i) {   
        }               
        }).show();
 }

谢谢您的回复,但是我该如何获取context?我正在使用androidx.appcompat.app.AlertDialog - Jeson Martajaya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接