I am creating a custom view in Android. In it\'s constructor I am obtaining some of the attributes that are set in the XML layout file. The code is like this:
pu
Although it is not documented, obtainStyledAttributes
expects a sorted array, and its code is optimized with that assumption.
So you need to provide your styledAttrs
array with the elements sorted in ascending order according to their id values.
There are several ways you can determine the correct order:
If you choose to sort the array programmatically at run time, make sure you use the appropriate (sorted) index when calling getString()
etc.
Another common workaround is to only get a single value with obtainStyledAttributes
at a time. (An array with one element is already sorted.)
Also I'm not sure if I should use the styledAttrs.getIndex(i) function or not
I believe that's only necessary if you're looping through the TypedArray
and its possible some of the elements may not have values; it basically "hides" the null elements for you as though it were a sparse array. In general I don't think it's necessary unless you're accessing styled resources in certain ways, for example when implementing a custom view.
Most of the time I use custom theme attributes that aren't related to a view at all, and in those cases I've always found TypedArray.getIndex()
to be redundant.