2014-09-29 89 views
87

我需要向用户显示一条短信,在我的Android应用程序上点击一个按钮,在IOS上我只需创建一个AlertView,它使用起来很简单,但对于Android我很挣扎,因为解决方案似乎比x10难多了。我看到我需要使用DialogFragment,但我无法理解如何使其工作,有人可以解释吗?另外,我的解决方案是否正确,还是有更简单的方式向用户显示简单的文本消息?Android简单警报对话框

回答

275

你可能只需要做到这一点在你的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简单示出警报知道。

希望这会有所帮助。

+6

仅供参考 - 在谷歌的Android开发人员网站上的第一个例子说明如何使用片段来做到这一点:http://developer.android.com /guide/topics/ui/dialogs.html 我认为这可能是导致开发人员认为他需要为基本AlertDialog使用片段的原因。我今天搜索,也许是这样想的。 – raddevus 2016-02-22 21:14:24

+1

最好在构建器上设置属性而不是alertDialog实例! – alexbirkett 2017-10-25 10:14:42

12

没有我的朋友它很简单,请尝试使用此:

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("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创建自定义对话框,然后告诉他们作为一个警告对话框。

+0

你还没有通过哪个按钮。 – Leon 2015-12-10 09:28:19

4

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

}