我们在自定义控件的时候,通常需要定义一些属性提供给用户,类似于一个接口,方便用户直接在xml文件中直接设置某些属性的值。
一、在attrs中自定义属性
在res/values下的atts.xml中定于你需要的属性。如果没有这个文件,那么就需要你在values下新建一个attrs.xml资源文件
这个attrs.xml文件内容通常是下面这种格式:
?
?
中给自己定义的属性所应用的控件起一个名字,这个名字用来在自定义控件中获取这个属性。
自定义你需要的属性名称,以及这个属性的类型。
一般属性的类型有下面这几种:
color:颜色值
boolean:布尔值
dimesion:尺寸值
float:浮点值
integer:整型值
string:字符串
fraction:百分数
enum:枚举值
reference:引用资源文件
二、在布局文件中使用自定义的属性
在我们使用自定义控件的布局文件中使用。
代码如下:
xmlns:myapp="http://schemas.android.com/apk/res/com.eyu.attrtextdemo"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
android:layout_height="wrap_content"
android:layout_width="wrap_content"
myapp:myTextSize="20sp"
myapp:myColor="#324243"/>
第一步:加入命名空间。格式如下
xmlns:起一个名字="http://schemas.android.com/apk/res/你的包名"
或者
xmlns:起一个名字="http://schemas.android.com/apk/res-auto"
第二步:在控件中使用。格式如下
命名空间的名字.自定义属性的名字 = "对应属性的值"
三、java代码中获取自定义属性的值
在java代码中获取用户设置的属性的值,然后用这些值来初始化一些参数。
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView);
int textColor = a.getColor(R.styleable.MyView_myColor, 003344);
float textSize = a.getDimension(R.styleable.MyView_myTextSize, 33);
paint.setTextSize(textSize);
paint.setColor(textColor);
a.recycle();
}
在自定义控件中三个方法的构造函数中,获取属性
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.这里就说自定义属性分类的名字);
int textColor = a.getColor(R.styleable.属性分类名_属性名, 默认值);
取到这些值就可以使用了。