Android custom view obtain multiple attributes

前端 未结 1 702
故里飘歌
故里飘歌 2021-01-26 19:43

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         


        
1条回答
  •  不思量自难忘°
    2021-01-26 20:09

    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:

    • based on their relative position in the resources
    • by checking their relative values and changing the array to match
    • or by sorting the array elements programmatically

    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.

    0 讨论(0)
提交回复
热议问题