繁体   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