Android 开发 TypedArray类 getResourceId的第二个参数是什么意思?
发布网友
发布时间:2022-04-25 00:05
我来回答
共2个回答
热心网友
时间:2023-10-16 18:51
第二个参数是defValue,代码中的意思是如果第一个参数没有找到对应的资源,则返回defValue设置的值。
举个例子
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidingDrawer, defStyle, 0);
int contentId = a.getResourceId(R.styleable.SlidingDrawer_content, 0);//比如这里,如果在xml中没有定义SlidingDrawer_content这个属性,则获取到的contentId 值是后面设置的0,如果定义了SlidingDrawer_content这个属性,则后面设置的默认值0无意义。
热心网友
时间:2023-10-16 18:51
给你看看这个方法的源码和注释
/**
* Retrieve the resource identifier for the attribute at
* <var>index</var>. Note that attribute resource as resolved when
* the overall {@link TypedArray} object is retrieved. As a
* result, this function will return the resource identifier of the
* final resource value that was found, <em>not</em> necessarily the
* original resource that was specified by the attribute.
*
* @param index Index of attribute to retrieve.
* @param defValue Value to return if the attribute is not defined or
* not a resource.
*
* @return Attribute resource identifier, or defValue if not defined.
*/
public int getResourceId(int index, int defValue) {
index *= AssetManager.STYLE_NUM_ENTRIES;
final int[] data = mData;
if (data[index+AssetManager.STYLE_TYPE] != TypedValue.TYPE_NULL) {
final int resid = data[index+AssetManager.STYLE_RESOURCE_ID];
if (resid != 0) {
return resid;
}
}
return defValue;
}
第二个参数叫做defValue,也就是default Value,默认值,如果你要取得的属性没有定义,或者不属于资源,就会返回这个defValue