Java TypedArray';中索引参数的用途是什么;什么是getColor()方法?

Java TypedArray';中索引参数的用途是什么;什么是getColor()方法?,java,android,xml,Java,Android,Xml,我很难理解索引参数对getColor()方法的作用。索引做什么?我应该如何使用它 在我当前的程序中,如果我将它保留为一些值,如0、1、2,那么颜色将始终为白色,而如果我将它设置为一个值,如5,那么它将是我选择的颜色 //makes color white TypedArray typedArray = obtainStyledAttributes(new int[]{R.attr.conversation_background}); int color = typedArray.getColo

我很难理解索引参数对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();

查看代码时,它看起来像“您选择的颜色”a.k.a.如果在数组中找不到该类型,将返回默认值。因此,在上一个示例中出现红色的原因是,它找不到任何其他内容可以返回给它的属性索引(5)


index
getColor(int-index,int-default)的参数匹配输入数组中请求的属性的索引


您只将1个项目数组传递给
获取样式属性(int[])
,因此您应该通过使用索引
0

获得所需的颜色,请使用自定义视图发布xml文件。
 * @param index Index of attribute to retrieve.
 * @param defValue Value to return if the attribute is not defined or
 *                 not a resource.