Я работаю с парсингом пользовательских атрибутов и наткнулся на что-то странное. Допустим, мой парсер выглядит примерно так:
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
. В чем разница между этими двумя методами, когда один позволяет мне получить атрибуты, а другой нет?