gpt4 book ai didi

android - "the returned color will be styled for the specified Context' s theme”是什么意思?

转载 作者:行者123 更新时间:2023-11-29 17:16:09 25 4
gpt4 key购买 nike

最近注意到一个方法

Context.getResources.getColor(int)

自 API 23 以来已弃用。应该改用

ContextCompat.getColor(context, R.color.your_color);

文档是这样说的:

int getColor (Context context, int id) Returns a color associated with a particular resource ID Starting in M, the returned color will be styled for the specified Context's theme.

但是,颜色将为特定主题设置样式是什么意思。颜色不是颜色吗?常数?主题中使用了预定义的颜色。那么如何设计呢?

最佳答案

来自 Resources 的文档 - int getColor (int id, Resources.Theme theme):

Returns a themed color integer associated with a particular resource ID. If the resource holds a complex ColorStateList, then the default color from the set is returned.

所以资源 id 可以不仅仅是一种简单的颜色,它可以指向这样的东西:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:color="@color/sample_focused" />
<item android:state_pressed="true"
android:state_enabled="false"
android:color="@color/sample_disabled_pressed" />
<item android:state_enabled="false"
android:color="@color/sample_disabled_not_pressed" />
<item android:color="@color/sample_default" />
</selector>

在这种情况下,返回的颜色将是 @color/sample_default

但是如果你想为颜色使用属性,像这样

    <item android:color="?attr/sample_default_color" />

您需要访问主题中的属性值才能完全解析颜色值。

根据 Alex Lockwood's blog post ,这些资源实际上并未附加到主题,如果您使用使用属性的颜色状态列表调用旧方法,则会抛出异常。在 Marshmallow 之前,由于此限制,您不能在颜色状态列表中使用属性。

关于android - "the returned color will be styled for the specified Context' s theme”是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38846547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com