【问题标题】:Programmatically set a view's color to ?android:attr color attributes以编程方式将视图的颜色设置为 ?android:attr 颜色属性
【发布时间】:2021-05-29 09:46:09
【问题描述】:

我需要以编程方式将视图的颜色设置为 ?android:attr/textColorPrimary,这是 android 的深色主题兼容属性中的一个属性。现在可以使用

获取colorButtonNormal
R.attr.colorButtonNormal

但不是 ?android:attr/textColorPrimary 和 ?android:attr/colorBackground。无论如何也可以通过编程方式获取这些属性?

【问题讨论】:

    标签: android android-dark-theme android-color


    【解决方案1】:

    您可以使用android.R.attr.textColorPrimary

    类似:

        val typedValue = TypedValue();
        theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
        val color = ContextCompat.getColor(this, typedValue.resourceId)
    

    在 Java 中:

    TypedValue typedValue = new TypedValue();
    getTheme().resolveAttribute(android.R.attr.colorSecondary, typedValue, true);
    int color = ContextCompat.getColor(this, typedValue.resourceId);
    

    【讨论】:

    • 谢谢你成功了。虽然我正在使用 java 进行编码,但它看起来有点不同。
    • @Prs2 我已经用 java 中的相同代码更新了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多