簡體   English   中英

TypedArray 的 getColor() 方法中的 index 參數的目的是什么?

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

我無法理解 index 參數對 getColor() 方法的作用。 索引有什么作用,我應該如何使用它?

在我當前的程序中,如果我將其保留為 0、1、2 等值,則顏色將始終為白色,而如果我將其設置為 5 等值,則它將是我選擇的顏色。

//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();

查看代碼,它看起來像“您選擇的顏色”,如果在數組中找不到該類型,則將返回默認值。 所以你在最后一個例子中變紅的原因是因為它找不到任何其他東西來返回你給它的屬性的索引 (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

getColor(int index, int default) index參數匹配輸入數組中請求屬性的索引。

您只將 1 個 item-array 傳遞給obtainStyledAttributes(int[])因此您應該使用索引0獲得所需的顏色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM