Reputation: 2621
I want to change the color of button press in a dialog like in the image below.
I managed to accomplish this when using simple Alert Dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Set dialog title
builder.setTitle(Html.fromHtml("<font color='#8b0000'>"
+ getResources().getString(R.string.delete_this_list)
+ "?" + "</font>"));
builder.setMessage(getResources().getString(R.string.delete)
+ " '"
+ lists[listNo]
+ "'?\n"
+ getResources().getString(
R.string.delete_this_list_description))
.setCancelable(false)
.setPositiveButton(getResources().getString(R.string.delete),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
//Some background stuff
//.......//
}
})
.setNegativeButton(
getResources().getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.show();
alertDialog.getButton(DialogInterface.BUTTON_POSITIVE)
.setBackground(getResources().getDrawable(R.drawable.btn_bar_holo_red));
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
.setBackground(getResources().getDrawable(R.drawable.btn_bar_holo_red));
But, this approach does not work when using DialogFragments. When using DialogFragments, there is no getButton method.
Any ideas??
Upvotes: 0
Views: 2080
Reputation: 4549
Instead of:
alertDialog.getButton(DialogInterface.BUTTON_POSITIVE) .setBackground(getResources().getDrawable(R.drawable.btn_bar_holo_red));
Try:
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button positiveButton = ((AlertDialog) dialog)
.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setBackgroundResource(R.drawable.btn_bar_holo_red_full);
Button negativeButton = ((AlertDialog) dialog)
.getButton(AlertDialog.BUTTON_NEGATIVE);
negativeButton.setBackgroundResource(R.drawable.btn_bar_holo_red_full);
}
});
Where btn_bar_holo_red_full would be defined in it's own xml file as follows:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed" android:state_pressed="true" />
<item android:drawable="@drawable/button_focused" android:state_focused="true" />
<item android:drawable="@drawable/button_default" />
</selector>
Then define button_pressed, button_focused and button_default as follows (you'll need three, one each for pressed, focused and default):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" androuid:shape="rectangle">
<solid android:color="@color/btn_background_pressed" />
</shape>
All that's left to do is to add those color values to your color.xml file.
Upvotes: 2