1、自定义属性文件attrs.xml,放入values文件夹中---------attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="myView">
<attr name="textColor" format="color"/>
<attr name="textSize" format="dimension"/>
</declare-styleable>
</resources>
2、自定义MyView类此类必须继承View基类 ------MyView.java
package cn.com.flyfot.attrs;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
private static final String TAG = "MyView";
private Paint mPaint;
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attr) {
super(context, attr);
mPaint = new Paint();
//获取自定义属性
TypedArray a = context.obtainStyledAttributes(attr, R.styleable.myView);
//获取尺寸属性值,默认大小为:30
float textSize = a.getDimension(R.styleable.myView_textSize, 30);
//获取颜色属性值,默认颜色为:0x990000FF
int textColor = a.getColor(R.styleable.myView_textColor, 0x990000FF);
//设置画笔的尺寸和颜色
mPaint.setTextSize(textSize);
mPaint.setColor(textColor);
//缓存属性,可以不设置,主要是为了提高效率
a.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(new Rect(10 ,10,300,300), mPaint);
}
}
3、main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:flyfot="http://schemas.android.com/apk/res/cn.com.flyfot.attrs"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!-- 设置属性 -->
<cn.com.flyfot.attrs.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
flyfot:textSize="120px"
flyfot:textColor="#ABCDEFEF"
/>
<!--
注意引入命名空间:xmlns:flyfot="http://schemas.android.com/apk/res/cn.com.flyfot.attrs"
-->
</LinearLayout>
备注:
系统在解析main.xml文件时,将实例化MyView类然后当前设置的属性上,就调用onDraw方法画到屏幕上去。