I have simple MaterialAlertDialog
and i want to setIcon for postive button. So i set icon programmatically since i want unique icon for multiple alert dialog, and use same theme for all dialog
Here is how i done.
final MaterialAlertDialogBuilder dialogBuilder = new MaterialAlertDialogBuilder(SubListActivity.this, R.style.AlertDialogTheme);
dialogBuilder.setTitle("Delete selected files ?");
ListView modeList = new ListView(SubListActivity.this);
modeList.setPadding(50,50,50,50);
CustomArrayAdapter adapter = new CustomArrayAdapter(SubListActivity.this, temp);
modeList.setAdapter(adapter);
dialogBuilder.setView(modeList);
dialogBuilder.setNegativeButton(android.R.string.no, null);
dialogBuilder.setPositiveButton(R.string.delete, (dialog, which) -> {
//Some function
}).setPositiveButtonIcon(getDrawable(R.drawable.ic_item_delete)).create().show();
Theme
<style name="AlertDialogTheme" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
<item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
<item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
</style>
<style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
<item name="rippleColor">@color/primarySubText</item>
<item name="android:textColor">@color/primarySubText</item>
</style>
<style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Icon">
<item name="rippleColor">@color/secondaryLightColor</item>
<item name="android:textColor">@color/darkRed</item>
<item name="iconTint">@color/darkRed</item>
<item name="iconSize">4dp</item>
<item name="iconPadding">4dp</item>
</style>
result:
If i set icon in theme the size fits button. But as i mentioned earlier i want to set unique icon for ever dialog.
So how do i adjust icon size ?
fun showAlert(): AlertDialog {
// for example we have drawable
val drawable: Drawable = ContextCompat.getDrawable(activity, R.drawable.positive)
// our material dialog builder
val alertDialogBuilder = MaterialAlertDialogBuilder(activity, R.style.AlertDialogStyle)
/**
then do something here, set title, body, etc..
*/
// get alert dialog from builder
val alertDialog = alertDialogBuilder.create()
// for example, we add drawable to positive button
alertDialog.setOnShowListener {
// now we can get positive button from alertDialog
val positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
// text size of our button
val textSize = positiveButton.textSize.toInt()
// drawable. we set size here
val positiveDrawableResized = drawable.apply { setBounds(0, 0, textSize, textSize) }
// add drawable to button
positiveButton.setCompoundDrawables(positiveDrawableResized, null, null, null)
// positive button click listener (if needed)
positiveButton.setOnClickListener { alertDialog.dismiss() }
}
// finally, show dialog
alertDialog.show()
return alertDialog
}