首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获取自定义属性(attrs.xml)的值?

如何获取自定义属性(attrs.xml)的值?
EN

Stack Overflow用户
提问于 2016-08-16 05:38:31
回答 2查看 2.5K关注 0票数 0

我在attrs.xml上声明了这个属性:

代码语言:javascript
复制
<resources>
    <attr name="customColorPrimary" format="color" value="#076B07"/>
</resources>

我需要得到它的值,它应该是"#076B07",但我得到的是一个整数:"2130771968“

我以这种方式访问该值:

代码语言:javascript
复制
int color = R.attr.customColorFontContent;

有没有一种正确的方法来获得这个属性的实际值?

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-16 05:45:35

不,这不是正确的方式,因为整数R.attr.customColorFontContent是Android Studio在编译您的应用时生成的资源标识符。

相反,您需要从主题中获取与属性相关联的颜色。使用以下类来完成此操作:

代码语言:javascript
复制
public class ThemeUtils {
    private static final int[] TEMP_ARRAY = new int[1];

    public static int getThemeAttrColor(Context context, int attr) {
        TEMP_ARRAY[0] = attr;
        TypedArray a = context.obtainStyledAttributes(null, TEMP_ARRAY);
        try {
            return a.getColor(0, 0);
        } finally {
            a.recycle();
        }
    }
}

然后您可以像这样使用它:

代码语言:javascript
复制
ThemeUtils.getThemeAttrColor(context, R.attr.customColorFontContent);
票数 4
EN

Stack Overflow用户

发布于 2016-08-16 05:46:39

您应该访问color属性,如下所示:

代码语言:javascript
复制
public MyCustomView(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, 0, 0);
    try {
        color = ta.getColor(R.styleable.MyCustomView_customColorPrimary, android.R.color.white); //WHITE IS THE DEFAULT COLOR
    } finally {
        ta.recycle();
    }

    ...
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38963465

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档