自定义组件<二> : TypeArray的用法与介绍

来源:互联网 发布:淘宝备份模板找不到了 编辑:程序博客网 时间:2024/06/05 07:35
接下来就给大家讲解一下TypeArray的用法:
  TypeArray介绍:
TypedArray typeArray = context.obtainStyledAttributes(attrs,
    R.styleable.titlebar, 0, 0);
TypeArray是一个类型数组,也是一个十分重要的属性容器。用于存放各种属性的资源。
其实例化的时候用context.obtainStyledAttributes来得到。
其中attrs是第一个参数,是一个AttributeSet的类型。
其中第二个是一个int[] attrs,
关于这个:api文档上市这样写的:

Return a StyledAttributes holding the attribute values in set that are listed in attrs. In addition, if the given AttributeSet specifies a style class (through the "style" attribute), that style will be applied on top of the base attributes it defines.

Be sure to call StyledAttributes.recycle() when you are done with the array.

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

其意为:

 返回一个StyledAttributes控股属性值设置在attrs上市。此外,如果给定AttributeSet指定一个样式类(通过“风格”属性),这种风格将被应用的基本属性,它定义了。  一定要调用StyledAttributes.recycle()当你完成数组。  在确定一个特定属性的最终值时,有四个符号是七折作用的:


其中resource是跟标签,可以在里面定义若干个declare-styleable,<declare-styleable name="MyView">中name定义了变量的名称,下面可以再自定义多个属性,针对<attr name="myTextSize" format="dimension"/>来说,其属性的名称为"myTextSize",format指定了该属性类型为dimension,只能表示字体的大小。

format还可以指定其他的类型比如;

reference   表示引用,参考某一资源ID
string   表示字符串
color   表示颜色值
dimension   表示尺寸值
boolean   表示布尔值
integer   表示整型值
float   表示浮点值
fraction   表示百分数
enum   表示枚举值
flag   表示位运算

 最后要调用ReCycle()方法。

注意的是既然是自定义组件,一定要在XML文件中写入:

xmlns:app="http://schemas.android.com/apk/res/com.xxx(包名)"

否则报错的话,就是未写入它引起的。

在下面的环节中,会详细的介绍自定义组件的用法


0 0