我已经定义了颜色的自定义样式属性。
<declare-styleable name="CustomView">
<attr name="custom1" format="boolean" />
<attr name="custom2" format="reference|color" />
</declare-styleable>
通过getStyleStyledAttributes获取xml中定义的属性时,即使xml中未定义任何属性,它也始终返回size为1。
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CustomView, 0, 0);
final int size = attributes.getIndexCount();
for(int i = 0; i < size; i++) {
final int attr = attributes.getIndex(i);
if (attr == R.styleable.CustomView_custom1) {
boolean b = attributes.getBoolean(attr, false);
}
else if (attr == R.styleable.CustomView_custom2) {
ColorStateList cs = attributes.getColorStateList(attr);
int color = cs.getDefaultColor();
}
}
即使在xml中未定义任何属性,此处的大小也始终为1。由于该颜色会获得一些随机值,因此不确定从何处获取一些值?
输出如下:
Test﹕ ----
Test﹕ CustomView= 2130772048
Test﹕ CustomView= 2130772049
Test﹕ ----
Test﹕ AttributeSet= 16842901 textSize
Test﹕ AttributeSet= 16842904 textColor
Test﹕ AttributeSet= 16842927 gravity
Test﹕ AttributeSet= 16842960 id
Test﹕ AttributeSet= 16842966 paddingLeft
Test﹕ AttributeSet= 16842968 paddingRight
Test﹕ AttributeSet= 16842996 layout_width
Test﹕ AttributeSet= 16842997 layout_height
Test﹕ AttributeSet= 16843000 layout_marginTop
Test﹕ AttributeSet= 16843101 singleLine
Test﹕ AttributeSet= 16843119 drawableLeft
Test﹕ AttributeSet= 16843121 drawablePadding
Test﹕ AttributeSet= 16843139 layout_toRightOf
Test﹕ AttributeSet= 2130772048 custom1
奇怪的问题。我只能建议您添加调试日志输出并尝试更改,以获取更多有关发生的情况的信息。
这些语句AttributeSet
在布局XML中转储您的自定义视图的属性ID和自定义视图的实例的ID 。
Log.i("Test", "----");
for (int id : R.styleable.CustomView) {
Log.i("Test", "CustomView= " + id);
}
Log.i("Test", "----");
int n = attrs.getAttributeCount();
for (int i = 0; i < n; i++) {
Log.i("Test", "AttributeSet= " + attrs.getAttributeNameResource(i) + " " + attrs.getAttributeName(i));
}
要查看是否custom2
在主题中设置了属性,请执行以下操作:
TypedValue val = new TypedValue();
boolean resolved = context.getTheme().resolveAttribute(R.attr.custom2, val, true);
if (resolved) {
Log.i("Test", "Custom2 in theme");
} else {
Log.i("Test", "Custom2 NOT in theme");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句