【发布时间】:2011-12-06 19:14:09
【问题描述】:
我正在解析自定义属性,但遇到了一些奇怪的事情。假设我的解析器看起来像这样:
final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.Item);
final int size = attributes.getIndexCount();
for(int i = 0; i < size; i++) {
final int attr = attributes.getIndex(i);
if(attr == R.styleable.Item_custom_attrib) {
final int resourceId = attributes.getResourceId(attr, -1);
if(resourceId == -1)
throw new Resources.NotFoundException("The resource specified was not found.");
...
}
attributes.recycle();
这行得通。现在,如果我将第 2 行替换为 final int size = attributes.length();,这意味着我得到了:
final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.Item);
final int size = attributes.length();
for(int i = 0; i < size; i++) {
final int attr = attributes.getIndex(i);
if(attr == R.styleable.Item_animation_src) {
final int resourceId = attributes.getResourceId(attr, -1);
if(resourceId == -1)
throw new Resources.NotFoundException("The resource specified was not found.");
...
}
attributes.recycle();
这与我抛出的 Resources.NotFoundException 一起崩溃。换句话说,attributes.getResourceId(attr, -1); 返回默认的-1 值。
现在,在这种特殊情况下,只有一个自定义属性。 attributes.getIndexCount() 和 attributes.length() 都返回 1,因为我的属性中确实有一个值。这意味着getIndex(i) 应该返回相同的数字,但事实并非如此。这意味着getIndexCount() 不仅仅是return the number of indices in the array that have data。这两种方法到底有什么区别,一种允许我获取属性而另一种不允许?
【问题讨论】: