android - Android材质按钮采用颜色原色而不是颜色重音
问题描述
我的布局按钮为 -
<com.google.android.material.button.MaterialButton
android:id="@+id/save_button"
style="@style/buttonView"
android:text="Save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
在我的styles.xml
,我有 -
<style name="buttonView" parent="Theme.MyTheme">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginStart">16dp</item>
<item name="android:layout_marginLeft">16dp</item>
<item name="android:layout_marginTop">16dp</item>
<item name="android:layout_marginEnd">16dp</item>
<item name="android:layout_marginRight">16dp</item>
</style>
在我的themes.xml
,我有 -
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.MyTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="android:textColorPrimary">@color/black</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!--- Accent color. -->
<item name="colorAccent">@color/red</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant
</item>
<!-- Customize your theme here. -->
</style>
</resources>
根据 Android 文档,所有 UI 元素(例如 FAB、textview、编辑文本、按钮)都采用颜色强调。所以我希望我的按钮colorAccent
默认采用,但为什么要采用colorPrimary
. 我做错什么了吗?
解决方案
你可以查看官方文档。
填充按钮具有backgroundTint
基于colorPrimary
.
同样在您的buttonView
样式中,您应该扩展提供的样式之一:
Default style Widget.MaterialComponents.Button
Icon style Widget.MaterialComponents.Button.Icon
Unelevated style. Widget.MaterialComponents.Button.UnelevatedButton
Unelevated icon style Widget.MaterialComponents.Button.UnelevatedButton.Icon
例子:
<style name="buttonView" parent="Widget.MaterialComponents.Button">
</style>
如果要更改背景颜色,可以:
backgroundTint
在您的自定义样式中使用该属性使用(最佳解决方案)覆盖
colorPrimary
自定义样式中的属性materialThemeOverlay
例子:
<style name="buttonView"parent="Widget.MaterialComponents.Button">
<item name="materialThemeOverlay">@style/CustomButtonThemeOverlay</item>
</style>
<style name="CustomButtonThemeOverlay">
<item name="colorPrimary">@color/...</item>
</style>
推荐阅读
- tensorflow - 如何在 datalab 上导出 tensorflow 模型以在 bigquery 中使用?
- python - 为什么这段代码不产生具有随机颜色的形状?
- asp.net-mvc - 向 ASP.NET MVC 中的重载方法添加不同的视图
- javascript - 数据操作:如何从我的数据数组中附加路径?
- python - 将 lambda 函数绑定到按钮在 for 循环中不起作用
- php - 在用户看到页面之前替换字符串
- html - 如何匹配文本在不同元素中的位置?
- uiviewcontroller - SwiftUI 开启推送 UIViewController
- excel - 使用 VBA 复制/粘贴多张图片(Excel 到 Outlook)
- plsql - 外键无法识别父键