Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Icon not shown in AlertDialog

Tags:

android

I have an alert dialog that does not show the icon that I set using "setIcon".
I use Android Studio and Android Emulator API 19/ Android 4.4.2.

I can run the app, the dialog is shown without icon, no error.
But Android studio marks the line that contains "setIcon" and offers me "Introduce local variable" and "Make method call chain into call sequence"

So my question : Why is the icon not shown?

My Code:

AlertDialog.Builder builder = new AlertDialog.Builder(this );  

builder

.setMessage("Repeat game?")
.setIcon(android.R.drawable.ic_dialog_alert)         //<--- icon does not show
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        //Yes button clicked, do something

    }
})
.setNegativeButton("No", null)                      //Do nothing on no
.show();
like image 203
Spacewalker Avatar asked Feb 23 '15 08:02

Spacewalker


4 Answers

Your title is empty, so android will not display it, therefore no icon will be shown either.

Set it to empty string:

builder.setTitle("")...<all the other stuff>
like image 61
Juanjo Vega Avatar answered Oct 24 '22 08:10

Juanjo Vega


You should use something like this:

builder.setIcon(getResources().getDrawable(android.R.drawable.ic_dialog_alert));

Try this :)

like image 27
Alejandro Martínez Martínez Avatar answered Oct 24 '22 08:10

Alejandro Martínez Martínez


You just need to add title, because the position of your icon is beside your title.

.setTitle("Attention")
.setIcon(android.R.drawable.ic_dialog_alert)  
like image 3
ahmfarisi Avatar answered Oct 24 '22 06:10

ahmfarisi


It might be that you need to set the title as well. If you do not like the new layout you might want to look at this question.

AlertDialog.Builder builder = new AlertDialog.Builder(this );  
builder
    .setMessage("Repeat game?")
    .setTitle("")
    .setIcon(android.R.drawable.ic_dialog_alert)         //<--- icon does not show
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            //Yes button clicked, do something
        }
    })
    .setNegativeButton("No", null)                      //Do nothing on no
    .show();
like image 2
mach Avatar answered Oct 24 '22 07:10

mach