获取想要得到的风格设计属性描述————Resources.Theme类函数public TypedArray obtainStyledAttributes()

今天看到一个群友问一个函数问题,看着挺有用的就研究了下。

看了帮助文档觉得下面这个method该是最复杂了,能囊括其他几个了吧。

当然本人初学,只是觉得今天自己算是很花脑子的把这个函数联系其他的思考了一番,怕以后忘了,应该不完全正确,只是要记录下用心思考的瞬间。。。

public TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)

照文档翻译是,返回一个设计样式属性包含了set里面的attrs参数:

AttributeSet 是一个由资源xml文件获得的各属性接口类(具体还有待研究,只是看文档下的代码推敲的)

XmlPullParser parser = resources.getXml(myResouce);
AttributeSet attributes = Xml.asAttributeSet(parser);

而int[] attrs 描述里是指定自己想要获取的属性项。所以我觉得大意是获取AttributeSet类成员里的attrs指定的成员。

接着是提取属性的优先级:

When determining the final value of a particular attribute, there are four inputs that come into play:

  1. Any attribute values in the given AttributeSet.    
  2. The style resource specified in the AttributeSet (named     "style").    
  3. The default style specified by defStyleAttr and     defStyleRes
  4. The base values in this theme.

第一优先级:AttributeSet里指定的属性

。二。。。:在AttributeSet里指定的名为"style"的风格资源(这个和第一点的区别不知道是不是整体和个别的区别以后用到的再研究下)

。三。。。:由参数defStyleAttr和defStyleRes指定的默认属性(PS:这样设计或许是为了可以自定义一个接口名在这以后想替换的时候把前面两个参数补全就行)

。四。。。:主题默认

例如你在AttributeSet里设置了 <Button textColor="#ff000000">,则此Button文字只会是黑色而不管其他风格里怎么设计。

返回一个TypedArray,该是存储属性的数组。当使用它时必须调用TypedArray.recycle()

Parameters
set         The base set of attribute values.  May be null.
attrs         The desired attributes to be retrieved.
defStyleAttr    An attribute in the current theme that contains a reference to a style resource that supplies defaults values for the StyledAttributes.  Can be 0 to not look for defaults.当前主题的默认风格属性来自一个风格设计资源的引用。能为0或者不再寻找默认(上面优先级的第四个)

defStyleRes    A resource identifier of a style resource that supplies default values for the StyledAttributes,used only if defStyleAttr is 0 or can not be found in the theme.  Can be 0 to not look for defaults.一个风格类资源的ID,只当defStyleAttr为0或者找不到时使用.

原文地址:https://www.cnblogs.com/DonkeyTomy/p/2609971.html