我在attrs.xml上声明了这个属性:
<resources>
<attr name="customColorPrimary" format="color" value="#076B07"/>
</resources>我需要得到它的值,它应该是"#076B07",但我得到的是一个整数:"2130771968“
我以这种方式访问该值:
int color = R.attr.customColorFontContent;有没有一种正确的方法来获得这个属性的实际值?
谢谢
发布于 2016-08-16 05:45:35
不,这不是正确的方式,因为整数R.attr.customColorFontContent是Android Studio在编译您的应用时生成的资源标识符。
相反,您需要从主题中获取与属性相关联的颜色。使用以下类来完成此操作:
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();
}
}
}然后您可以像这样使用它:
ThemeUtils.getThemeAttrColor(context, R.attr.customColorFontContent);发布于 2016-08-16 05:46:39
您应该访问color属性,如下所示:
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();
}
...
}https://stackoverflow.com/questions/38963465
复制相似问题