最近我从支持库切换到com.google.android.material:material:1.0.0
但现在我有一个问题,在这个页面上有一个注释https://github.com/material-components/material-components-android/blob/master/docs/getting-started.md
注意:使用“材质成分”主题可启用自定义视图填充程序,该填充程序将使用“材质”对应项替换默认组件。目前,这仅使用MaterialButton替换Button XML组件。
我正在使用的主题
Theme.MaterialComponents.Light.NoActionBar
完全按照它在说明中所说的,它将AlertDialog按钮替换为MaterialButtons,但问题是默认情况下MaterialButtons是彩色背景,现在按钮看起来像这样:
我怎样才能让它们再次无边界和无背景?
PS我正在使用警报构建器来创建警报对话框:
android.app.AlertDialog.Builder
我弄清楚导致这个问题的原因。我需要使用不同的AlertDialog类:
androidx.appcompat.app.AlertDialog
当我切换到这一切时,一切都按预期开始工作。这是我找到解决方案的地方:
https://github.com/material-components/material-components-android/issues/162
使用com.google.android.material:material:1.0.0
和androidx.appcompat.app.AlertDialog
时,您可以使用buttonBar
作为父级来自定义Widget.MaterialComponents.Button.TextButton
中的每个按钮。
val builder: AlertDialog.Builder = AlertDialog.Builder(ContextThemeWrapper(context, R.style.AlertDialogTheme))
使用默认布局或通过builder.setView(R.layout.my_dialog)
添加自定义
在你的风格:
<style name="AlertDialogTheme" parent="Theme.MaterialComponents.Light.Dialog.Alert">
<item name="buttonBarPositiveButtonStyle">@style/Alert.Button.Positive</item>
<item name="buttonBarNegativeButtonStyle">@style/Alert.Button.Neutral</item>
<item name="buttonBarNeutralButtonStyle">@style/Alert.Button.Neutral</item>
</style>
<style name="Alert.Button.Positive" parent="Widget.MaterialComponents.Button.TextButton">
<item name="backgroundTint">@color/transparent</item>
<item name="rippleColor">@color/colorAccent</item>
<item name="android:textColor">@color/colorPrimary</item>
<item name="android:textSize">14sp</item>
<item name="android:textAllCaps">false</item>
</style>
<style name="Alert.Button.Neutral" parent="Widget.MaterialComponents.Button.TextButton">
<item name="backgroundTint">@color/transparent</item>
<item name="rippleColor">@color/colorAccent</item>
<item name="android:textColor">@color/gray_dark</item>
<item name="android:textSize">14sp</item>
</style>
在这里使用MaterialComponents找到了另一个解决方案:https://issuetracker.google.com/issues/116861837#comment9
<style name="Theme.Custom.Material.Alert.Dialog.Light" parent="Theme.MaterialComponents.Light.Dialog.Alert">
<item name="materialButtonStyle">@style/Widget.AppCompat.Button.Borderless</item>
</style>
<style name="Theme.Custom.Material.Base.Light" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="android:dialogTheme">@style/Theme.Custom.Material.Alert.Dialog.Light</item>
<item name="android:alertDialogTheme">@style/Theme.Custom.Material.Alert.Dialog.Light</item>
....
</style>
虽然它仍然不是我的“预期行为”。
如果您使用com.android.support:design:28.0.0
库,使用android.support.v7.app.AlertDialog
按预期工作。
如果您不想使用androidx.appcompat.app.AlertDialog
,您可以重新定义对话框按钮的样式:
在你的style.xml中:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
...
<item name="android:buttonBarButtonStyle">@style/DialogButton</item>
...
</style>
<style name="DialogButton" parent="Widget.MaterialComponents.Button.TextButton"/>