Android自定义属性的步骤
在我们自定义View的过程中,我们经常需要为自己的View添加一些自定义的属性,用来完善我们的自定义view,下面我来介绍下如何为自己的控件自定义属性。
自定义属性一般分为如下几个步骤
在res/values/attrs.xml文件中使用attr标签和declare-styleable定义自定义属性
在布局文件中使用自定义的属性
在代码中获取自定义属性,用于初始化控件
定义自定义属性
自定义属性的格式
这里我只写出了基本格式,由于网上已经有人总结的很详细了,我就不再过多介绍,所有属性的定义和使用方法,请查看
在布局文件中使用自定义的属性
下面的com.jay.customattr.CoustomView是我们继承自View的自定义类,可以看到,我们在他的里面使用了jay:text和jay:color属性,其中text和color是上一步中我们自定义的属性,这里的jay指的是xmlns(xml namespace xml文件命名空间),我们在RelativeLayout里面可以看到android自带的命名空间的申明格式如下。
xmlns:android="http://schemas.android.com/apk/res/android"
我们自己定义的属性的xmlns的定义格式为
Eclipse : xmlns:名字(本例中为jay)="http://schemas.android.com/apk/res+包名" 也就是程序的包名,在AndroidManifest.xml的package里面,直接复制过来就行。
Android Studio : xmlns:名字(本例中为jay)="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:jay="http://schemas.android.com/apk/res/com.jay.customattr"
android:layout_width="match_parent"
android:layout_height="match_parent" >
android:layout_width="match_parent"
android:layout_height="match_parent"
jay:text="自定义属性的文字"
jay:color="#ccffff" />
在代码中获取自定义属性,用于初始化控件
在代码中获取属性值,需要使用TypedArray类,大致流程是,使用context.obtainStyledAttributes()获取所有属性值,然后根据属性值的id调用不同的get函数,最后TypedArray对象必须显示的回收,也就是调用recycle()方法。属性值的id为R.styleable."declare-able的name"_"attr的name",中间是一个下划线隔开。这里初始化的代码全部放在三个参数的构造函数中,然后在一个参数的里面调用两个参数的构造函数,最终调用三个参数的构造函数。
package com.jay.customattr;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class CoustomView extends View {
public CoustomView(Context context) {
this(context, null);
}
public CoustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CoustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CoustomView, defStyleAttr, 0);
int attrCount = a.getIndexCount();
for (int i = 0; i < attrCount; i++) {
switch (a.getIndex(i)) {
case R.styleable.CoustomView_text:
Log.v("x", a.getString(i));
break;
case R.styleable.CoustomView_color:
Log.v("x", a.getColor(i, 0xffffff) + "");
break;
}
}
a.recycle();
}
}
本文只是简单的介绍了自定义属性的流程,关于具体原理可以查看