在定義view的時候,咱們能夠使用系統提供的屬性,也能夠自定義些額外的屬性來設置自定義view的樣式,這個時候,咱們就須要TypeArray,字面意思就是Type 數組。android
今天咱們就講講如何自定義View的屬性。數組
TypeArray是和xml文件聯合使用,在android中,不少都是和xml文件聯合使用的。函數
咱們在res/value 路徑下建立一個attr.xml文件,這個文件裏面能夠包含若干個屬性集合。】orm
<?xml version='1.0' encoding="utf-8"?>xml
<resource>utf-8
<declare-styleable name="MyView">io
<attr name="myTextSize" format="dimension"/> format是數據類型form
<attr name="myColor" format="color"/>coding
</declare-styleable>構造函數
</resource>
在構造函數中,經過TypeArray ta = context.obtainStyledAttributes(attrs,R.styleable.MyView,defstyle,0);
這樣就得到屬性集合,而後經過調用ta提供的方法來獲取自定義控件在使用過程當中在頁面設置的屬性值。這裏的目的是獲取這些屬性值,在繪製這個自定義view的時候要使用到。
在獲取到這些值之後,必須調用ta.recycle()方法,回收。