<?xml version="1.0" encoding="utf-8"?><resources xmlns:android="http://schemas.android.com/apk/res/android"><!-- declare CustomView2 style --><declare-styleable name="CustomView2"><attr name="textColor" format="color" /><attr name="backgroundColor" format="color" /></declare-styleable></resources>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"xmlns:app="http://schemas.android.com/apk/res/com.gaoyuan4122.customui"android:layout_width="match_parent"android:layout_height="match_parent" ><TextViewandroid:id="@+id/tv_hello"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/hello_world" /><com.gaoyuan4122.customui.views.CustomView1android:id="@+id/cv_custom1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/tv_hello" /><TextViewandroid:id="@+id/tv_hello2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/hello_world"android:layout_below="@id/cv_custom1" /><com.gaoyuan4122.customui.views.CustomView2android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/tv_hello2"app:backgroundColor="#ff00ff"app:textColor="#ffff00" /></RelativeLayout>
private int mTextColor;private int mBackgroundColor;public CustomView2(Context context) {this(context, null);}public CustomView2(Context context, AttributeSet attrs) {this(context, attrs, 0);}- // 自定义属性会被封装到 attrs 中, 第三个参数和样式有关, 这里先不说.
public CustomView2(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);// 通过下面的方法去除自定义属性TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomView2);mTextColor = typedArray.getColor(R.styleable.CustomView2_textColor, Color.RED);mBackgroundColor = typedArray.getColor(R.styleable.CustomView2_backgroundColor, Color.BLUE);// 最后一定要注意调用这个方法, 至于为什么后面会说.typedArray.recycle();}
@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);mPaint.setStyle(Style.FILL);mPaint.setColor(mBackgroundColor);mRect.set(0, 0, 100, 100);canvas.drawRect(mRect, mPaint);mPaint.setColor(mTextColor);mPaint.setTextSize(30.0f);canvas.drawText("Hello!", 0, 100, mPaint);}

原文:http://www.cnblogs.com/ywq-come/p/5927303.html