先說一下attrs.xml文件。這個文件定義了自定義View的屬性的信息,包括屬于哪個控件屬性的名稱,屬性的類型。下面是一個普通的attrs.xml的內(nèi)容
<resources>
<declare-styleable name = “MyView”>
<attr name = “textColor” format = “color”></attr>
<attr name = “textSize” format = “dimension”/>
</declare-styleable>
</resources>
其中標(biāo)簽declare-styleable的name屬性代表了接下來定義的屬性的所屬控件(只是用來區(qū)分不同declare-styleable的代號而且,不一定非要和屬性相關(guān)的控件的名稱一致)。標(biāo)簽attr就是用來的定義具體的屬性,name代表屬性名,format代表屬性的類型。
Attrs.xml文件中屬性類型format值的格式
引用型reference
定義:<attr name = “background” format = “reference” />
使用:Tools:background = “@drawable/圖片ID”
顏色型color
定義:<attr name = “textColor” format = “color” />
使用:tools:textColor = “#ffffff”
布爾型boolean
定義:<attr name = “focusable” format = “boolean” />
使用:tools: focusable = “true”
尺寸型dimension
定義:<attr name = “l(fā)ayout_width” format = “dimension” />
使用:tools: layout_width = “42dip”
浮點型float
定義:<attr name = “fromAlpha” format = “float” />
使用:tools: fromAlpha = “1.0”
整型integer
定義:<attr name = “frameDuration” format = “integer” />
使用:tools: frameDuration = “100”
字符串string
定義:<attr name = “apiKey” format = “string” />
使用:tools: apiKey = “dsegergegasefwg”
百分?jǐn)?shù)fraction
定義:<attr name = “pivotX” format = “fraction” />
使用:tools: pivotx = “200%”
屬性定義可以指定多種類型:
定義:< attr name = "background" format = "reference|color" />
使用:android:background = "@drawable/圖片ID|#00FF00"
TypedArray
與Context類的obtainStyledAttributes方法一起使用,作為一個不同類型的數(shù)據(jù)的容器使用。使用是如:
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);
這句一般是使用在自定義View的構(gòu)造方法中的,其中attrs是構(gòu)造方法的形參,而R.styleable.MyView是和attrs.xml相關(guān)的。MyView是attrs.xml中declare-styleable的name屬性的值。如果這個自定義View在attrs.xml文件中對應(yīng)的declare-styleable的name屬性值為A,那么這里就寫R.styleable.A
其中包括很多方法,用來獲取這個容器中包含的值
·getColor獲取顏色值
·getDimension獲取尺寸值
這些方法一般都有這兩個參數(shù)int index, int defValue。其中index為用來查找屬性的檢索值。如果實在attrs.xml文件中定義的屬性,就是R.styleable.xxxx_yyyy。Xxxx代表declare-styleable的name值,yyyy代表attr的name值。
defValue代表默認(rèn)值,即如果在xml文件中沒有設(shè)置,可以使用默認(rèn)值來進行設(shè)置。
AttributeSet是一個屬性的集合,與一個在XML文件中的標(biāo)簽相聯(lián)系。如在自定義View中,構(gòu)造方法中會有一個AttributeSet類型的參數(shù),這個參數(shù)就和XML中定義的自定義View相聯(lián)系的。一般不需要直接使用它。