Android 自定義view時用到的TypedArray

前言:

在自定義控件的時候,如果我們想額外的添加一些屬性,就會用到TypedArray這個類,那麼這個類是怎麼得到的,以及怎麼使用的,這裏作個簡單介紹。

創建自定義屬性

首先創建values\attrs.xml,在attrs.xml中聲明自定義屬性:

<declare-styleable name="MyFirstCustomerView">
    <attr name="text" format="string" />
    <attr name="textColor" format="color"/>
    <attr name="textSize" format="dimension"/>
</declare-styleable>
  • 自定義string類型,屬性名爲text
  • 自定義color類型,屬性名爲textColor
  • 自定義dimension類型,屬性名爲textSize

declare-styleable這個標籤的作用其實就是可以爲我們完成很多常量(int[]數組,下標常量)等的編寫,簡化我們的開發工作

format還有如下類型:

format 介紹
reference 表示引用,參考某一資源ID
string 表示字符串
color 表示顏色值
dimension 表示尺寸值
boolean 表示布爾值
integer 表示整型值
float 表示浮點值
fraction 表示百分數
enum 表示枚舉值
flag 表示位運算

自定義空間在xml裏面佈局的時候引用自定義的屬性。

CustomView是自定義控件,引用了app:text、app:textColor、 app:textSize="18sp"三個自定義屬性

<com.ligj.test.view.CustomView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:text="這是自定義屬性"
    app:textColor="@android:color/black"
    app:textSize="18sp"/>

當然,起作用的前提是,要在自定義的view裏面處理:

public class CustomView extends View {

public Paint paint;
private String text = "";//文本內容
private int textColor = 0xDD333333;  //字體顏色
private float textSize = 20;//字體大小設置

public CustomView(Context context) {
    this(context, null);
}

public CustomView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(attrs);
}

private void init(AttributeSet attrs) {
    TypedArray a = getResources().obtainAttributes(attrs, R.styleable.MyFirstCustomerView);//獲取TypedArray
    textColor = a.getColor(R.styleable.CustomerView_textColor, textColor);//獲取佈局中設置的自定以顏色
    textSize = a.getDimension(R.styleable.CustomerView_textSize, textSize);//獲取佈局中設置的自定義字體大小
    text = a.getString(R.styleable.CustomerView_text);//獲取佈局中設置的自定義文本
    paint = new Paint();//初始化 畫筆
    paint.setTextSize(textSize);//畫筆字體大小設置
    paint.setColor(textColor);//畫筆的顏色
    paint.setStyle(Paint.Style.FILL);//畫筆風格
    a.recycle();//切記:在使用TypedArray後需要回收
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawText(text, 100, 100, paint);
}}

-TypedArray用完一定要回收。其實obtainAttributes()底層是native方法,也就是用C++實現的,他會提取自定義控件屬性的的值保存TypedArray中的mData數組中,這個數組的大小是由你定義控件屬性的個數決定的,是它的6倍,上面的attrs其實就是你自定義屬性的個數。

Context 當前上下文
AttributeSet 爲xml裏一個節點下面的屬性的集合,這個類一般都是系統在生成有xml配置的組件時生成,可以理解爲當前自定義控件下的所有屬性集合;提供TypedArray檢索的範圍
defStyleAttr

在當前包含了一個引用到爲TypedArray提供默認值的樣式資源的theme中的一種屬性。可以爲0,但是爲0的時候就不會再去尋找默認的;提供TypedArray檢索的範圍(注:這裏的默認也就是defStyleRes)

總結

  • declare-styleable標籤可以爲我們完成很多常量(int[]數組,下標常量)等的編寫,簡化我們的開發工作,可以不聲明,但是需要在自定義控件中,聲明引用自定義屬性數組
  • TypedArray 可有obtainAttributes()、obtainStyledAttributes()方法創建,常用obtainStyledAttributes(int resid, int[] attrs)構造方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章