由于其他回答都没有提供自定义样式覆盖的方法(我认为这是最安全的更新方式之一),因此我在此发布我的解决方案。
我发布了一个解决方案,已经解决了新的 AndroidX
(support design 28
)主题。
假设您的应用程序在AndroidManifest.xml
中使用名为MyAppTheme
的自定义主题:
<application
android:name=".MyApplicationName"
android:allowBackup="true"
android:icon="@mipmap/icon"
android:roundIcon="@mipmap/icon_round"
android:label="@string/app_name"
android:theme="@style/MyAppTheme">
如果您还没有创建,那么请创建values/style.xml
文件,覆盖您的应用程序使用的主题:
<style name="MyAppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="colorPrimary">@color/myColorPrimary</item>
<item name="colorPrimaryDark">@color/myColorPrimaryDark</item>
<item name="colorAccent">@color/myColorAccent</item>
<item name="snackbarStyle">@style/MySnackBarStyle</item>
</style>
<style name="MySnackBarStyle" parent="Widget.MaterialComponents.Snackbar">
<item name="android:background">@color/mySnackbarBackgroundColor</item>
</style>
并在您的values/colors.xml
文件中提供您的颜色。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="myColorPrimary">#008577</color>
<color name="myColorPrimaryDark">#00574B</color>
<color name="myColorAccent">#D81B60</color>
<color name="mySnackbarBackgroundColor">#D81B60</color>
</resources>
2020年更新
由于上述解决方案移除了snackbar的圆角,因为以这种方式设置背景使用了传统的snackbar设计,如果您想保留Material Design,则可以:
- 如果您的目标是API 21+
将android:background
替换为android:backgroundTint
<style name="MySnackBarStyle" parent="Widget.MaterialComponents.Snackbar">
<item name="android:backgroundTint">@color/mySnackbarBackgroundColor</item>
</style>
如果您的目标API<21,则如果您决定在API<21中使用旧版snackbar,您可以将上述MySnackbarStyle
设置在res/values-21/文件夹中,并保留以前的遗留样式在您的res/values文件夹中。
如果您的目标API<21并且希望在这些较低的API级别中也具有snackbar的材料样式,则可以通过以下方式更改在res/values/中的snackbar样式:
<style name="MySnackBarStyle" parent="Widget.MaterialComponents.Snackbar">
<item name="android:background">@drawable/my_snackbar_background</item>
</style>
从 官方仓库 中借用你的 my_snackbar_background
,方式如下:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="4dp"/>
<solid android:color="@color/mySnackbarBackgroundColor"/>
</shape>
编辑于2022年:
如果您只想更改单个snackbar而不是整个应用程序,那么可以按照以下方式使用ContextThemeWrapper;
ContextThemeWrapper ctw = new ContextThemeWrapper(this, R.style.CustomSnackbarTheme);
customSnackBar = Snackbar.make(ctw, view, "", Snackbar.LENGTH_LONG);
并且在您的样式文件中
<style name="CustomSnackbarTheme">
<item name="snackbarStyle">@style/MySnackBarStyle</item>
</style>
<style name="MySnackBarStyle" parent="Widget.MaterialComponents.Snackbar">
<item name="android:background">@android:color/red</item>
</style>
这里有一个游乐场仓库。
![在这里输入图片描述](https://istack.dev59.com/tW1W7.webp)