How to show appropriate icon on dialog box

こ雲淡風輕ζ 提交于 2019-12-08 16:49:16

问题


I have an application that allows the users to delete video files. When I press the delete button, I am using

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;
        }
    }
};

But this message doesn't have a warning or delete icon as we see in android devices. Can anyone help me in getting those icons or using any other alert dialogs that can show those icons?


回答1:


I tend to use AlertDialog.Builder like they show in the official doc example

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

As for the actual icon look inside your sdk folder/platforms/android version #/data/res/drawable-mdpi or something




回答2:


In order to set the default Dialog icons use:

.setIcon(android.R.drawable.ic_dialog_alert)

There are a few more icons available:

  • android.R.drawable.ic_dialog_dialer
  • android.R.drawable.ic_dialog_info
  • android.R.drawable.ic_dialog_email
  • android.R.drawable.ic_dialog_map



回答3:


Just replace .setIcon(R.drawable.icon); to .setIcon(getResources().getDrawable(R.drawable.icon)); But it's deprecated.




回答4:


Another (dirty) way:

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

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



回答5:


You can also set certain icon for the Alert dialog buttons as:

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



来源:https://stackoverflow.com/questions/6693282/how-to-show-appropriate-icon-on-dialog-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!