属性值的类型(format)有以下几种:android
一、reference 引用类型值 : @id/...八、<enum> 枚举类型值 :水平/垂直数组
九、 flag:位或运算eclipse
十、fraction:百分数
布局
使用步骤:
1、定义属性: 在values目录下建立attrs.xml
ui
<declare-styleable name="suibianxue">
<attr name="roundColor" format="color"></attr>
<attr name="textColor" format="color"></attr>
<attr name="roundWidth" format="dimension"></attr>
<attr name="textSize" format="dimension"></attr>
</declare-styleable>
2、 在使用了自定义属性的xml布局文件中引用当前应用的命名空间:orm
eclipse中写成: xmlns:suibianxue="http://schemas.android.com/apk/res/应用包名" ( 其中suibianxie能够任意写, )xml
android studio中写成: xmlns:suibianxue="http://schemas.android.com/apk/res-auto" ( 其中suibianxie能够任意写, )
3、 在自定义视图标签中使用自定义属性
<com.example.customatrrs.MyTextView
android:id="@+id/mytextview"
android:layout_width="120dp"
android:layout_height="120dp"
对象
suibianxue:roundProgressColor="@android:color/holo_red_dark"
suibianxue:textColor="@color/text_progress"
suibianxue:roundWidth="10dp"
suibianxue:textSize="20sp" />
4、在自定义View类的构造方法中, 取出布局中的自定义属性值
一、获得全部自定义属性的数组 : TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.customatrrs);
二、获取自定义属性的值, 若是没有指定取默认值
roundColor = typedArray.getColor(R.styleable.RoundProgress_roundColor, Color.RED);
roundProgressColor = typedArray.getColor(R.styleable.RoundProgress_roundProgressColor, Color.GREEN);
textColor = typedArray.getColor(R.styleable.RoundProgress_textColor, Color.GREEN);
roundWidth = typedArray.getDimension(R.styleable.RoundProgress_roundWidth, UIUtils.dp2px(10));
textSize = typedArray.getDimension(R.styleable.RoundProgress_textSize, UIUtils.dp2px(20));
三、释放资源数据: typedArray.recycle();ip
代码Demo下载路径:
资源