1. 程式人生 > >Android自定義控制元件屬性(草稿版)

Android自定義控制元件屬性(草稿版)

 

 

常用的format型別:

1)  string:字串型別;
2)  integer:整數型別;
3)  float:浮點型;
4)  dimension:尺寸,後面必須跟dp、dip、px、sp等單位;
5)  Boolean:布林值;
6)  reference:引用型別,傳入的是某一資源的ID,必須以“@”符號開頭;
7)  color:顏色,必須是“#”符號開頭;
8)  fraction:百分比,必須是“%”符號結尾;
9)  enum:列舉型別

 

  <declare-styleable name="circleView">
        <attr name="textSize" format="dimension" />
        <attr name="text" format="string" />
        <attr name="circleColor" format="color" />
        <attr name="arcColor" format="color" />
        <attr name="textColor" format="color" />
        <attr name="startAngle" format="integer" />
        <attr name="sweepAngle" format="integer" />
    </declare-styleable>

 

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="rightPadding" format="dimension" />

    <declare-styleable name="CustomMenu">
        <attr name="rightPadding" />
    </declare-styleable>
</resources> 

<resources>
    <attr name="orientation">
        <enum name="horizontal" value="0" />
        <enum name="vertical" value="1" />
    </attr>

    <declare-styleable name="CustomView">
        <attr name="orientation" />
    </declare-styleable>
</resources>

在XML佈局檔案中使用自定義的屬性時,我們需要先定義一個namespace。Android中預設的namespace是android,因此我們通常可以使用“android:xxx”的格式去設定一個控制元件的某個屬性,android這個namespace的定義是在XML檔案的頭標籤中定義的,通常是這樣的:

xmlns:android="http://schemas.android.com/apk/res/android"

  我們自定義的屬性不在這個名稱空間下,因此我們需要新增一個名稱空間。

  自定義屬性的名稱空間如下:

xmlns:app="http://schemas.android.com/apk/res-auto"

  可以看出來,除了將名稱空間的名稱從android改成app之外,就是將最後的“res/android”改成了“res-auto”。

  注意:自定義namespace的名稱可以自己定義,不一定非得是app。