Android高手之路之Android中的自訂屬性attr.xml、TypedArray的使用
一般我們都是使用android:xxx=...這樣的android的屬性。但有時我們需要使用自訂的屬性,尤其是自訂view的時候尤其需要。
一般需要以下幾個步驟:
1.在res/values 檔案下定義一個attrs.xml 檔案:
2.重寫我們的自訂View的構造方法。是使用R.styleable.MyView獲得我們的自訂屬性。
TypedArray 通常最後調用 .recycle() 方法,為了保持以後使用該屬性一致性!
package com.example.viewdemo;import android.annotation.SuppressLint;import android.content.Context;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 MyView extends View{ private Paint mPaint; private Context mContext; private static final String mString = oh,God!; public MyView(Context context) { super(context); } public MyView(Context context,AttributeSet attrs) { super(context,attrs); mPaint = new Paint(); TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView); int textColor = a.getColor(R.styleable.MyView_textColor, 0xffffff);//注意加預設值 float textSize = a.getDimension(R.styleable.MyView_textSize, 36); mPaint.setTextSize(textSize); mPaint.setColor(textColor); a.recycle(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //設定填充 mPaint.setStyle(Style.FILL); //畫一個矩形,前倆個是矩形左上方座標,後面倆個是右下角座標 canvas.drawRect(new Rect(10, 10, 100, 100), mPaint); mPaint.setColor(Color.BLUE); //繪製文字 canvas.drawText(mString, 10, 110, mPaint); }}
3.將我們的自訂屬性用在XML布局檔案中。注意首碼
運行效果: