< resources >
< declare-styleable name ="customView" >
< attr name ="android:textColor" />//在自定義屬性中使用Android自帶的屬性名字
< attr name ="customtextSize" format ="dimension" />//自定義屬性,format屬性表示該屬性的單位
</ declare-styleable >
</resources>
二、 我們在customView.java 代碼修改如下,其中下面的構造方法是重點,我們獲取定義的屬性R.sytleable.customView_android_textColor和R.sytleable.customView_customtextSize, 獲取方法中后面通常設定默認值(float textSize = a.getDimension(R.styleable. customView_customtextSize , 36 ); ), 防止我們在xml 文件中沒有定義.從而使用默認值!
獲取,customView 就是定義在<declare-styleable name="customView "></declare-styleable> 里的 名字,獲取里面屬性用 名字_ 屬性 連接起來就可以.TypedArray 通常最后調用 .recycle() 方法,為了保持以后使用該屬性一致性!
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
public class customView extends View{
private Paint mPaint;
private static final String mString = "Welcome to Mr Wei's blog";
public customView(Context context) {
super(context);
mPaint = new Paint();
// TODO Auto-generated constructor stub
}
public customView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.customView);
int textColor = a.getColor(R.styleable.customView_android_textColor, 0xff0000);
float textSize = a.getDimension(R.styleable.customView_customtextSize, 36);
mPaint.setColor(textColor);
mPaint.setTextSize(textSize);
a.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
//設置填充
mPaint.setStyle(Style.FILL);
//畫一個矩形,前倆個是矩形左上角坐標,后面倆個是右下角坐標
canvas.drawRect(new Rect(10, 10, 200, 200), mPaint);
mPaint.setColor(Color.BLUE);
//繪制文字
canvas.drawText(mString, 10, 110, mPaint);
}
}
三、將我們自定義的customView加入布局main.xml 文件中,平且使用自定義屬性,自定義屬性必須加上:
xmlns:test ="http://schemas.android.com/apk/res/com.lee0000.AutoCustomAttr "藍色 是自定義屬性的前綴,紅色 是我們包名.main.xml 全部代碼如下:
< LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android"
xmlns:test ="http://schemas.android.com/apk/res/com.lee0000.AutoCustomAttr"
android:layout_width ="fill_parent"
android:layout_height ="fill_parent"
android:orientation ="vertical" >
< TextView
android:layout_width ="fill_parent"
android:layout_height ="wrap_content"
android:text ="@string/hello" />
< com.lee0000.AutoCustomAttr.customView
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
test:customtextSize ="20dp"//自定義屬性
android:textColor ="#fff" >
</ com.lee0000.AutoCustomAttr.customView >
</ LinearLayout >
上一個demo下載:CustomAttrExample.zip