支持Dark& AndroidX中的浅色主题 [英] Supporting Dark & Light Theme in AndroidX

查看:332
本文介绍了支持Dark& AndroidX中的浅色主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I currently use the following parent theme Theme.MaterialComponents.Light.NoActionBar and just updated my material design library to

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

它弄乱了我的应用程序中的某些颜色

which messed up some colors in my app

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

So i am deciding to update it to support both light and dark themes. I will post what i did to achieve this to save some time for others searching

推荐答案

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

After performing some searches, this is what i did in details

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

Change the parent theme to 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>


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


    • Remove all background colors, text colors etc... where its necessary

      通过以下方式添加颜色:"?android:attr/colorBackground""?attr/colorOnBackground""?attr/colorSurface"需要的地方

      add colors this way: "?android:attr/colorBackground", "?attr/colorOnBackground", "?attr/colorSurface" where needed


      要更改代码中的某些颜色,然后使用此功能

          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
          }
      

      示例:

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

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

      示例:

      <?xml version="1.0" encoding="utf-8"?>
      <resources>
      
          <color name="colorPrimaryDark">#1f2021</color>
      
      </resources>
      

      这篇关于支持Dark&amp; AndroidX中的浅色主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆