lomza lomza - 12 days ago 5
Android Question

Set a background to buttons in a dialog?

I have a dialog, which works just fine for me, but I want to set my background for two buttons in this dialog. The structure of it is quite complicated so I don't want to rewrite it to a custom dialog. But in this case, is there any possibility to set a background(more specifically, is there a way to set a style to positive/negative/neutral buttons)?

Answer

Fundamentally you want to access the dialog buttons: these (on the standard AlertDialog) currently have ids android.R.id.button1 for positive, android.R.id.button2 for negative, and android.R.id.button3 for neutral.

So for example to set the background image on the neutral button you can do this:

Dialog d;
//
// create your dialog into the variable d
//
((Button)d.findViewById(android.R.id.button3)).setBackgroundResource(R.drawable.new_background);

EDIT: this is if you are using an AlertDialog.Builder to create it. For all I know these button assignments may change in the future, so keep that in mind.

EDIT: The chunk of code below should generate something that looks like what you want. It turns out you have to call show BEFORE you change the background

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("TEST MESSAGE)
        .setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        })
        .setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
((Button)alert.findViewById(android.R.id.button1)).setBackgroundResource(R.drawable.button_border);
Comments