在 AndroidX 中支持深色和浅色主题 [关闭]

2023-12-19

我目前使用以下父主题Theme.MaterialComponents.Light.NoActionBar刚刚更新了我的材料设计库

implementation 'com.google.android.material:material:1.1.0'

这弄乱了我的应用程序中的一些颜色

所以我决定更新它以支持浅色和深色主题。我将发布我为实现此目标所做的工作,以节省其他人搜索的时间


执行一些搜索后,这就是我所做的详细信息

将父主题更改为Theme.MaterialComponents.DayNight.NoActionBar

    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
      <item name="android:navigationBarColor">@color/transparent</item>
      <item name="android:windowContentTransitions" tools:targetApi="lollipop">true</item>
      <item name="colorPrimary">@color/colorPrimary</item>
      <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
      <item name="colorSecondary">@color/colorAccent</item>
    </style>

  • 必要时删除所有背景颜色、文本颜色等...

  • 这样添加颜色:"?android:attr/colorBackground", "?attr/colorOnBackground", "?attr/colorSurface"在需要的地方


To change some colors in-code then use this function
    fun getColor(context: Context, colorResId: Int): Int {
       val typedValue = TypedValue()
       val typedArray = context.obtainStyledAttributes(typedValue.data, intArrayOf(colorResId))
       val color = typedArray.getColor(0, 0)
       typedArray.recycle()
       return color
    }

Example:

setTextColor(Utils.getColor(context, R.attr.colorError))


  • 如有必要,添加values-night目录以支持深色和夜间模式下的不同颜色
  • 在目录中添加colors.xml文件,然后覆盖colors.xml中写入的任何颜色

Example:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <color name="colorPrimaryDark">#1f2021</color>

</resources>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 AndroidX 中支持深色和浅色主题 [关闭] 的相关文章

随机推荐