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 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.debby.attrs" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <!-- 设置属性 --> <cn.debby.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.debby.attrs" --> </LinearLayout>