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)?
You can just create a style and apply that theme on the dialog box. So whenever you want to change the color of AlertDialog box, just change color in styles. xml and all the dialog boxes will be updated in the whole application.
int colornumber=((ColorDrawable)v. getBackground()). getColor(); This is the best and simple way to get the color of a View (Button, TextView...)
This example demonstrate about how to make custom dialog in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
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);
Actually there's a better and more reliable way to get the buttons for the Dialog
than the one posted by @Femi .
You can use the getButton method:
Button positiveButton = yourDialog.getButton(DialogInterface.BUTTON_POSITIVE);
The DialogInterface provides all the needed constants:
DialogInterface.BUTTON_POSITIVE
DialogInterface.BUTTON_NEUTRAL
DialogInterface.BUTTON_NEGATIVE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With