我目前使用以下父主题Theme.MaterialComponents.Light.NoActionBar
,刚刚将我的材料设计库更新为
implementation 'com.google.android.material:material:1.1.0'
这弄乱了我的应用程序中的一些颜色
所以我决定更新它以支持浅色和深色主题。我将发布我为实现这一目标所做的工作,以节省其他人搜索的时间
我目前使用以下父主题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"
在需要的地方
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))
示例:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimaryDark">#1f2021</color>
</resources>
对于黑暗主题:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
对于普通主题:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
您可以根据需要在 oncreate 和 button click 等中设置主题。
values
文件夹的styles.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:textColorPrimary">@android:color/black </item>
</style>
</resources>
将文件夹添加到该添加中的文件res
夹名称和您的需要。
文件夹的styles.xmlvalues-night
color.xml
style.xml
values-night
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/orange</item>
<item name="colorPrimaryDark">@color/orangeDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:textColorPrimary">@android:color/white</item>
</style>
color.xml
文件values
夹
<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
<color name="daynight_textColor">#6cbabb</color>
</resources>
color.xml
文件values-night
夹
<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
<color name="daynight_textColor">#ff8222</color>
</resources>