Android中自定義屬性的使用

 自定義屬性: 是指定義可以在佈局文件的標籤中使用的屬性。如TextView控件中的Text屬性,但是它是由系統提供的,現如今是由我們自己定義。
使用自定義視圖屬性的好處: 這樣就可以通過佈局xml的方式給視圖對象指定自己定義的任意屬性值, 而不是僅僅只能使用系統中內定的屬性啦。

屬性值的類型(format)有如下幾種:

             1、reference 引用類型值 : @id/...
             2、 color 顏色類型值     #ff00ff
             3、 boolean 布爾類型值    true , false
             4、 dimension 尺寸類型值     dp / px /sp
             5、 integer 整數類型值       weight  progress max
             6、float 浮點型值        0.1f
             7、string 字符串類型值  "atrrs"

             8、<enum> 枚舉類型值 :水平/垂直

             9、 flag:位或運算

            10、fraction:百分數

使用步驟:
     一、定義屬性: 在values目錄下創建attrs.xml

            <declare-styleable name="suibianxue">
                  <attr name="roundColor" format="color"></attr>               
                  <attr name="textColor" format="color"></attr>
                  <attr name="roundWidth" format="dimension"></attr>
                  <attr name="textSize" format="dimension"></attr>
             </declare-styleable>

     二、 在使用了自定義屬性的xml佈局文件中引用當前應用的命名空間:

                   eclipse中寫成:  xmlns:suibianxue="http://schemas.android.com/apk/res/應用包名"  ( 其中suibianxie可以任意寫,   )

                  android studio中寫成:  xmlns:suibianxue="http://schemas.android.com/apk/res-auto" ( 其中suibianxie可以任意寫,  )

    三、 在自定義視圖標籤中使用自定義屬性
           <com.example.customatrrs.MyTextView
                android:id="@+id/mytextview"
                android:layout_width="120dp"
                android:layout_height="120dp"

                suibianxue:roundProgressColor="@android:color/holo_red_dark"
                suibianxue:textColor="@color/text_progress"
                suibianxue:roundWidth="10dp"
                suibianxue:textSize="20sp"  />
 

四、在自定義View類的構造方法中, 取出佈局中的自定義屬性值
        1、得到所有自定義屬性的數組   : TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.customatrrs);
           
       2、獲取自定義屬性的值, 如果沒有指定取默認值
                 roundColor = typedArray.getColor(R.styleable.RoundProgress_roundColor, Color.RED);
                  roundProgressColor = typedArray.getColor(R.styleable.RoundProgress_roundProgressColor, Color.GREEN);
                  textColor = typedArray.getColor(R.styleable.RoundProgress_textColor, Color.GREEN);
                  roundWidth = typedArray.getDimension(R.styleable.RoundProgress_roundWidth, UIUtils.dp2px(10));
                 textSize = typedArray.getDimension(R.styleable.RoundProgress_textSize, UIUtils.dp2px(20));

     3、釋放資源數據: typedArray.recycle();

   代碼Demo下載路徑:


          



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章