问题
I need a dialog with custom background color and rounded corners. How can I keep default layout params using custom window background for AlertDialog?
Currently, my dialog has smaller left-right margin than in regular dialog. Also, dialog buttons such as positive and neutral have more shift from the edge of dialog.
<style name="DialogStuffTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowBackground">@drawable/bg_custom</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:gravity">center</item>
</style>
bg_custom.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="270"
android:startColor="@color/Cyan200"
android:endColor="@color/Green200"
android:type="linear" />
<corners
android:radius="@dimen/dialog_corner_radius" />
</shape>
</item>
</selector>
回答1:
Should use this when creating AlertDialog: new AlertDialog.Builder(context, R.style.MyDialog)
<style name="DialogBarButton" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
<item name="android:textColor">@color/button_bar_enabled_selector</item>
</style>
<style name="DialogBase" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowMinWidthMajor">@dimen/dialog_min_width_major</item>
<item name="android:windowMinWidthMinor">@dimen/dialog_min_width_minor</item>
<item name="android:windowAnimationStyle">@style/Animation.AppCompat.Dialog</item>
<item name="android:buttonBarButtonStyle">@style/DialogBarButton</item>
</style>
<style name="MyDialog" parent="DialogBase">
<item name="android:windowBackground">@drawable/bg_custom</item>
</style>
values/dimens.xml:
<dimen name="dialog_min_width_major">65%</dimen>
<dimen name="dialog_min_width_minor">85%</dimen>
color/button_bar_enabled_selector.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/colorAccent" android:state_enabled="true" />
<item android:color="@color/TextDisabled"/>
</selector>
I don't know why color of dialog bar buttons had changed in this case. To fix this issue I have to use selector with colors for enabled and disabled states.
来源:https://stackoverflow.com/questions/48988795/keep-alertdialog-default-layout-params-using-custom-window-background