自定义View不得不知道的事情:自定义属性

来源:互联网 发布:js 输入结束事件 编辑:程序博客网 时间:2024/06/05 22:47

申明:好记性不如烂笔头,做记录仅供自己参考;

attr和styleable的关系:

attr不依赖于styleable,styleable只是为了方便attr的使用。我们自己定义属性完全可以不放到styleable里面,比如直接在resources文件中定义(先定义后使用)一些属性:

<attr name="custom_attrs1" format="string" /><attr name="custom_attrs2" format="string" />

使用:

int[]custom_attrs={R.attr.custom_attrs1,R.attr.custom_attrs2};TypedArray typedArray = context.obtainStyledAttributes(set,custom_attrs);

or 修改attrs文件:

<declare-styleable name="custom_attrs">     <attr name="custom_attr1" format="string" />    <attr name="custom_attr2" format="string" /></declare-styleable> 

使用

TypedArra typedArray = context.obtainStyledAttributes(set,R.styleable.custom_attrs);

obtainStyledAttributes函数获取属性去使用:

  • obtainAttributes(AttributeSet set, int[] attrs) //从layout设置的属性集中获取attrs- 中的属性
  • obtainStyledAttributes(int[] attrs) //从系统主题中获取attrs中的属性
  • obtainStyledAttributes(int resId,int[] attrs) //从资源文件定义的style中读取属性
  • obtainStyledAttributes (AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)//这是最复杂的一种情况,后面细说。

我们只需要掌握参数就知道怎么使用了:

  • set: 表示从layout文件为这个View直接添加的属性集合,如:android:layout_width=”“。注意,这里面的属性必然是通过xml配置添加的,也就是由LayoutInflater加载进来的布局或者View`才有这个属性集。
  • attrs:int[],每个方法中都有的参数,就是告诉系统需要获取那些属性的值。
  • defStyleAttr:
比如你要给所有字体定义一个样式,让他们生效<style name="textviewstyle" parent="android:style/Widget.TextView">    <!--指定一些属性--></style>在参数中使用: public TextView(Context context, AttributeSet attrs) {    //指定属性textViewStyle为defStyleAttr,然后系统会去搜索Theme中你为这个    //属性配置的style    this(context, attrs, com.android.internal.R.attr.textViewStyle);  }
  • defStyleRes:默认的样式,如果theme中存在就使用theme的样式;优先级最低

优先级:最上层的是theme(theme谁最后使用会把前面的替换)>Style(set中的)>attrs(自定义的属性值)

 上项目:https://github.com/qinmr/Custom_attribute.git

TypedArray

我们看到在获取到属性值之后,都会返回一个TypedArray对象,它又是什么鬼?TypedArray主要有两个作用,第一是内部去转换attrid和属性值数组的关系;第二是提供了一些类型的自动转化,比如我们getString时,如果你是通过@string/hello这种方式设置的,TypedArray会自动去将ResId对应的string从资源文件中读出来。说到底,都是为了方便我们获取属性参数。

0 0
原创粉丝点击