【问题标题】:Android simple alert dialog [duplicate]Android简单的警报对话框[重复]
【发布时间】:2014-11-23 16:55:24
【问题描述】:

我需要向在我的 Android 应用程序上单击按钮的用户显示一条小短信,在 IOS 上,我只需要创建一个简单易用的 AlertView,但在 Android 上我正在苦苦挣扎,因为该解决方案似乎是 x10 次更难。我看到我需要使用 DialogFragment 但我不明白如何使它工作,有人可以解释一下吗?另外,我的解决方案是否正确,或者是否有更简单的方法可以向用户显示简单的短信?

【问题讨论】:

    标签: android dialog android-alertdialog


    【解决方案1】:

    您只需在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 来简单地显示警报。

    【讨论】:

    • 仅供参考 - Google 的 Android Dev 网站上的第一个示例展示了如何使用 Fragment 执行此操作:developer.android.com/guide/topics/ui/dialogs.html 我认为这可能是导致开发人员认为他需要使用 Fragment 进行基本操作的原因警报对话框。我今天搜索并认为可能是这样。
    • 最好在构建器上设置属性而不是在 alertDialog 实例上!
    【解决方案2】:

    不,我的朋友,它很简单,试试这个:

    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();
    

    这个tutorial 展示了如何使用 xml 创建自定义对话框,然后将它们显示为警报对话框。

    【讨论】:

    • 你没有通过哪个按钮。
    【解决方案3】:

    您可以轻松制作自己的“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();
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 2011-08-24
      相关资源
      最近更新 更多