如何在对话框中显示相应的图标

11

我有一个允许用户删除视频文件的应用程序。当我按下删除按钮时,我使用的是

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
        case DialogInterface.BUTTON_POSITIVE:
            // mycode........
            break;
        case DialogInterface.BUTTON_NEGATIVE:
            // mycode.....
            break;
        }
    }
};

但是这个消息没有像我们在Android设备中看到的警告或删除图标。有人可以帮我获取这些图标或使用其他可以显示这些图标的警告对话框吗?


1
请发布您创建AlertDialog的代码。 - Alexander Mikhaylov
先生,我已经使用了对话框(不是警报对话框),并且想要一个使用警报对话框的示例。你可以给我一个吗? - Farhan
6个回答

36

我倾向于像官方文档示例中展示的那样使用AlertDialog.Builder。

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
   .setCancelable(false)
   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            MyActivity.this.finish();
       }
   })
   .setNegativeButton("No", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
       }
   })
   //Set your icon here
   .setTitle("Alert!")
   .setIcon(R.drawable.icon);
AlertDialog alert = builder.create();
 alert.show();//showing the dialog

至于实际图标的外观,可以在sdk文件夹/platforms/android版本#/data/res/drawable-mdpi或其他位置找到。


1
我尝试设置可绘制对象,但它没有显示在对话框中。 - Farhan
1
嗯,尝试设置一个标题。我认为这可能是你没有看到标题的原因。尝试使用我的编辑代码。 - Kevin Qiu
非常感谢您,先生。它起作用了。您能否告诉我更多关于其他功能,例如将图像放在中心等。再次感谢。 - Farhan
为此,您需要创建一个带有自定义预定义视图的自定义对话框。 - Kevin Qiu
1
@AlamKanak 你的编辑是错误的... setIcon() 是重载方法,既可以接受 Drawable 实例也可以接受可绘制资源 ID! - Xaver Kapeller

9
为了设置默认对话框图标,请使用以下方法:
.setIcon(android.R.drawable.ic_dialog_alert)

还有几个可用的图标:

  • android.R.drawable.ic_dialog_dialer:电话图标
  • android.R.drawable.ic_dialog_info:信息图标
  • android.R.drawable.ic_dialog_email:邮件图标
  • android.R.drawable.ic_dialog_map:地图图标

0

另一种(不太正规的)方法:

TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(android.R.attr.alertDialogIcon, typedValue, true);

new AlertDialog.Builder(this)
    .setIcon(typedValue.resourceId)
    ...
    .show();

0

您还可以为警报对话框按钮设置特定的图标,如下所示:

builder.setPositiveButtonIcon(getResources().getDrawable(drawable.ic_menu_share))


0

.setIcon(R.drawable.icon); 替换为 .setIcon(getResources().getDrawable(R.drawable.icon));,但这已经过时了。


0

只需为您的AlertDialog设置标题。像这样:

adb.setTitle(R.string.app_name);

完整示例:

AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setIcon(R.mipmap.ic_launcher_foreground);
adb.setTitle(R.string.app_name);
adb.show();

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