【问题标题】:Apply color from theme attr value to AppCompatTextView programatically以编程方式将主题属性值中的颜色应用于 AppCompat TextView
【发布时间】:2021-02-10 18:59:06
【问题描述】:

我正在尝试使用 setColor 方法设置 AppCompatTextView 的文本颜色,并从我的主题中的自定义属性提供颜色,但它似乎不起作用。

以下是我正在使用的确切代码

binding.loginTextTv.setTextColor(R.attr.primaryMainColor)

当我做类似的事情时它工作正常

binding.loginTextTv.setTextColor(R.color.primaryColor)

如何更改主题属性的颜色?

我的自定义属性看起来像

<resources>
  <attr name="primaryMainColor" type="color"/>
</resources>

【问题讨论】:

    标签: android xml material-design themes


    【解决方案1】:

    您应该传递的不是参考,而是这样的颜色:
    ContextCompat.getColor(context, R.color.primaryColor)

    或者如果你想获得主题颜色试试这个:

    /**
     * Retrieves colors from theme attributes
     *
     * @throws Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
     * @throws UnsupportedOperationException if the attribute is defined but is
     *         not an integer color or color state list.
     */
    @ColorInt
    @SuppressLint("Recycle")
    fun Context.getThemeColor(@AttrRes colorAttrId: Int): Int {
      return obtainStyledAttributes(intArrayOf(colorAttrId))
        .use { it.getColor(0, Color.WHITE) }
    }
    

    drawable.setTint(requireContext().getThemeColor(android.R.attr.colorBackground))

    或者可能是您的自定义属性不属于视图(在遍历属性时它不会在内部解析它) 所以解决方案是从AppCompatTextView 创建一个派生类并解析init() 上的自定义属性。

    【讨论】:

    • 太棒了。我需要在设置之前将主题属性解析为颜色。知道了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多