android自定義XML佈局屬性

1.查看源碼,定義屬性時候做法

        sdk所在目錄\platforms\android-16\data\res\values\attrs.xml

        TextView佈局屬性:
        <resource>
            <declare-styleable name="TextView">
                <attr name="text" format="string"/>
            </declare-styleable>
        <resource>

2.給自己定義的View定義屬性,工程res\values\attrs.xml

     在values中創建attrs.xml
        <resource>
            <declare-styleable name="全類名">
                <attr name="屬性名" format="屬性類型"/>
                <attr name="test" format="string"/>
            </declare-styleable>
        <resource>

3.自定義屬性的使用

    定義命名空間
    demo替換掉原有android
    自己的包名替換掉了android,代表當前應用自定義屬性
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:demo="http://schemas.android.com/apk/res/包名"

    在佈局中使用:demo:test="測試"

4.獲取屬性值

在有兩個參數或者三個參數的構造方法中寫以下代碼,最好是在有三個參數的構造方法中寫。
//通過屬性索引獲取屬性名稱&屬性值
for(int i=0;i<attrs.getAttributeCount();i++){
    //獲取屬性名
    Log.i(tag, "name = "+attrs.getAttributeName(i));
    //獲取屬性值
    Log.i(tag, "value = "+attrs.getAttributeValue(i));
    Log.i(tag, "分割線 ================================= ");
}
//通過屬性獲取屬性名稱&名空間
命名空間="http://schemas.android.com/apk/res/包名"
mDestitle = attrs.getAttributeValue(命名空間, "屬性名");
發佈了19 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章