attrs.xml AttributeSet TypedArray obtainStyledAttributes

来源:互联网 发布:北风网大数据项目实战 编辑:程序博客网 时间:2024/05/21 11:36

如下attrs相关内容转自:http://www.cnblogs.com/mstk/p/3575086.html


控件有很多属性,如android:id、android:layout_width、android:layout_height等,但是这些属性都是系统自带的属性。使用attrs.xml文件,可以自定义属性。本文在Android自定义控件的基础上,用attrs.xml文件自己定义了属性。

首先,在values文件夹下,新建一个attrs.xml文件,文件内容如下:

1
2
3
4
5
6
7
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomView">
        <attr name="tColor" format="color" />
        <attr name="tSize" format="dimension" />
    </declare-styleable>    
</resources>

其中,<declare-styleable name="CustomView">表明样式名称为CustomView,下面包含了两个自定义属性tColor和tSize,其中tColor是颜色(color)类的属性,tSize是尺寸(dimension)类的属性。


如下AttributeSet  TypedArray 相关内容转自:http://blog.csdn.net/bingospunky/article/details/39890053


AttributeSet这个类就是代表xml里一个节点下面的属性的集合,这个类一般都是系统在生成有xml配置的组件时生成,我们一般不去生成该对象,使用的时候一般都是把AttributeSet封装成TypedArray进行使用


TypedArray

我认为这个类是学习自定义属性最重要的,首先来看它是什么:

[java] view plain copy
 print?
  1. Container for an array of values that were retrieved with Resources.Theme.obtainStyledAttributes(AttributeSet, int[], intint) or Resources.obtainAttributes. Be sure to call recycle when done with them. The indices used to retrieve values from this structure correspond to the positions of the attributes given to obtainStyledAttributes.  

是一个用于存放恢复obtainStyledAttributes(AttributeSet, int[], int, int)或 obtainAttributes(AttributeSet, int[])  值的一个数组容器,当操作完成以后,一定要调用recycle()方法。用于检索的索引值在这个结构对应的位置给obtainStyledAttributes属性

它就是属性的集合,我们获取属性一般就是这个类的.getxxx()方法。

重点是学习这个类的实例是怎么来的?一般是由context.obtainStyledAttributes这个方法,有4个重载的方法。

我们来看

[java] view plain copy
 print?
  1. TypedArray android.content.Context.obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)  

这个方法就是从资源里挑出一些属性来,按照顺序放到TypedArray里,参数可以控制从哪里挑选属性,挑选哪些。

参数set:挑选属性的出处是AttributeSet。

参数attrs:这是一个属性的数组,只是哪些属性被挑选出来,在之前看R文件的时候R.styleable.button1就是这样的数组,我们可以自己new这样的数组,再赋值。

参数defStyleAttr:挑选属性的出处是defStyleAttr。

参数defStyleRes:挑选属性的出处是defStyleRes。


android中怎么在View构造的attrs中拿到android给的属性


在自定义view的代码中引入自定义属性,修改构造函数context通过调用obtainStyledAttributes方法来获取一个TypeArray,然后由该TypeArray来对属性进行设置obtainStyledAttributes方法有三个,我们最常用的是有一个参数的obtainStyledAttributes(int[] attrs),其参数直接styleable中获得TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView);调用结束后务必调用recycle()方法,否则这次的设定会对下次的使用造成影响




代码部分:









0 0
原创粉丝点击