简体   繁体   中英

What is the purpose of the index argument in TypedArray's getColor() method?

I am having trouble understanding what index argument does for the getColor() method. What does index do and how should I use it?

In my current program, if I leave it to some values like 0, 1, 2, then the color will always be white, whereas if I put it to a value like 5, then it will be the color I choose.

//makes color white

TypedArray typedArray = obtainStyledAttributes(new int[]{R.attr.conversation_background});
int color = typedArray.getColor(1, Color.WHITE);
typedArray.recycle();

//makes color white

TypedArray typedArray = obtainStyledAttributes(new int[]{R.attr.conversation_background});
int color = typedArray.getColor(1, Color.RED);
typedArray.recycle();

//makes color white

TypedArray typedArray = obtainStyledAttributes(new int[]{R.attr.conversation_background});
int color = typedArray.getColor(5, Color.WHITE);
typedArray.recycle();

//makes color red

TypedArray typedArray = obtainStyledAttributes(new int[]{R.attr.conversation_background});
int color = typedArray.getColor(5, Color.RED);
typedArray.recycle();

Looking through the code it looks like "the color you choose" aka the default value will be returned if the type is not found in the array. So the reason you get red on your last example is because it couldn't find anything else to return for the index of the attribute you gave it (5).

 * @param index Index of attribute to retrieve. * @param defValue Value to return if the attribute is not defined or * not a resource.

https://android.googlesource.com/platform/frameworks/base.git/+/master/core/java/android/content/res/TypedArray.java

index argument of getColor(int index, int default) matches index of requested attribute in input array.

You're only passing 1 item-array to obtainStyledAttributes(int[]) so You should be getting your desired color by using index 0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM