从样式更改Snackbar的动作颜色

4
我需要将AppTheme.colorAccent设置为棕色,但是我需要我的Snackbar操作按钮颜色为蓝色。如何在不改变AppTheme.colorAccent的情况下更改Snackbar操作按钮的颜色?
我尝试了这个代码,但它没有起作用:
<style name="TextAppearance.Design.Snackbar" parent="android:TextAppearance" tools:override="true">
    <item name="colorAccent">#3097ff</item>
</style>
2个回答

5
使用 Material Components 库,您可以实现这一点。
只需在您的应用程序主题中添加 `snackbarButtonStyle` 属性即可。
<style name="AppTheme" parent="Theme.MaterialComponents.*">
    <!-- Style to use for action button within a Snackbar in this theme. -->
    <item name="snackbarButtonStyle">@style/snackbar_button</item>
    ...
</style>

然后定义您的自定义样式:
  <style name="snackbar_button" parent="@style/Widget.MaterialComponents.Button.TextButton.Snackbar">
      <item name="backgroundTint">@color/secondaryLightColor</item>
      <item name="android:textColor">@color/primaryDarkColor</item>
  </style>

图片描述在此输入

它需要1.1.0版本的库。


必须使用Material3库v1.8.0这样做,否则操作文本似乎会被硬编码为粉色。 - Slion

0

您可以在colors.xml中定义颜色,并在snackbar中使用它,如下所示:

val mySnackbar = Snackbar.make(findViewById(R.id.container),"Item added to cart.", Snackbar.LENGTH_SHORT)
mySnackbar.setAction("view cart", View.OnClickListener {/*action to be triggered*/  })
mySnackbar.setActionTextColor(/*color defined*/)
mySnackbar.show()

我用 Kotlin 实现了这个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接