我为颜色定义了自定义样式属性..
<declare-styleable name="CustomView">
<attr name="custom1" format="boolean" />
<attr name="custom2" format="reference|color" />
</declare-styleable>
当通过obtainStyledAttributes获取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
答案 0 :(得分:1)
奇怪的问题。我只能建议你添加调试日志输出并试验变化,以便更好地了解正在发生的事情。
这些语句转储自定义视图的属性ID,并在布局XML中转储自定义视图实例的AttributeSet
。
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");
}
答案 1 :(得分:0)
对我来说,问题是这样的:
private fun init(attrs: AttributeSet?) {
post {
val attributes = context.theme.obtainStyledAttributes(
attrs,
R.styleable.CustomButton,
0, 0
)
.....
如果我在帖子中获得了属性{},则没有。这可行:
private fun init(attrs: AttributeSet?) {
val attributes = context.theme.obtainStyledAttributes(
attrs,
R.styleable.CustomButton,
0, 0
)
post {
....