Iterating over an AttributeSet Enumeration
I have the following code:
private static boolean hasTargetStyle(AttributeSet attributes) {
final Enumeration<?> attributeNames = attributes.getAttributeNames();
while (开发者_JAVA技巧attributeNames.hasMoreElements()) {
final Object attributeName = attributeNames.nextElement();
if (attributeName.equals(MY_STYLE_NAME)) {
return true;
}
}
return false;
}
Now I would think this code would step through each of the attribute names. But it's only giving me every other attribute name (the ones with even-numbered indices).
What's going wrong here?
I don't think it has an index - a Set
doesn't have index. And the code looks fine. Unless the getAttributeNames()
returns a wrongly-implementation enumeration, it should work.
I don't see anything wrong with your code at the moment, but try using Collections.list
private static boolean hasTargetStyle(AttributeSet attributes) {
final List<?> attributeNames = Collections.list(attributes.getAttributeNames());
for(Object name: attributeNames){
if(name.equals(MY_STYLE_NAME)){
return true;
}
}
return false;
}
I doubt that this is a problem with java.util.Enumeration
(although this is just an interface and the actual implementation may have a bug). Your implementation looks good to me.
Other idea: The initial AttributeSet
may only contain every other attribute. Try to set a breakpoint and have a look at the internals of an actual attribute set.
The internal list I was looking at in the debugger had both names and values alternating. So, my code is correct in a certain sense, but my intent was wrong.
精彩评论