(三)自定義View實(shí)踐之自定義屬性

一、定義與聲明

自定義屬性xml文件.png

在資源文件夾values下新建attr.xml文件

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <attr name="text" format="string"/>
    <attr name="textColor" format="color"/>
    <attr name="textSize" format="dimension"/>

    <declare-styleable name="CodeView">
        <attr name="text"></attr>
        <attr name="textColor"></attr>
        <attr name="textSize"></attr>
    </declare-styleable>

</resources>

其中CodeView是自定義styleable名,可以隨意取
format有以下幾種:

  1. reference:參考某一資源ID
  2. color:顏色值
  3. boolean:布爾值
  4. dimension:尺寸值
  5. float:浮點(diǎn)值
  6. integer:整型值
  7. string:字符串
  8. fraction:百分?jǐn)?shù)
  9. enum:枚舉值
  10. flag:位或運(yùn)算

二、具體使用

具體的解析需要自行來做對(duì)應(yīng)的修改:

/**
     * 解析自定義屬性
     *
     * @param context
     * @param attrs
     */
    private void parseAttr(Context context, @Nullable AttributeSet attrs) {
        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CodeView);
        int num = attributes.getIndexCount();
        for (int i = 0; i < num; i++) {
            int attr = attributes.getIndex(i);
            switch (attr) {
                case R.styleable.CodeView_text:
                    mText = attributes.getString(attr);
                    break;
                case R.styleable.CodeView_textColor:
                    //默認(rèn)設(shè)置為黑色
                    mTextColor = attributes.getColor(attr, Color.BLACK);
                    break;
                case R.styleable.CodeView_textSize:
                    //默認(rèn)設(shè)置為16sp,TypeValue也可以把sp轉(zhuǎn)化為px
                    mTextSize = attributes.getDimensionPixelSize(attr, (int) TypedValue
                            .applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources()
                            .getDisplayMetrics()));
                    break;
            }
        }
        attributes.recycle();
    }

上述方法是在自定義View的構(gòu)造器中調(diào)用的:

public CodeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        parseAttr(context, attrs);
    }

    public CodeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        parseAttr(context, attrs);
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容