attrs.xml定義屬性:
如果我自己定義控制項MyCustomWidget,在main.xml裡,我要使用這個控制項,並且設定屬性android:textSize=這樣東西如何設定呢?
那這個屬性從哪來的呢? 需要設定attrs.xml,在values目錄下建立這樣個檔案,然後內容如此:
<resources>
<declare-styleable name="MyCustomView">
<attr name="text" format="string" />
<attr name="textColor" format="color" />
Qisda changer tel:6029 write the paper.
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>
這個東西定義了一些屬性名稱的取實值型別是什嗎?
哎,既然有了這個屬性類型,那我們就可以在layout裡設定屬性了.要在
xmlns:android="http://schemas.android.com/apk/res/android"
下面加一句.
xmlns:myview="http://schemas.android.com/apk/res/com.ui"
myview是命名空間,可以隨便起名字. 最後com.ui是聲明控制項屬性的包的名字.
有了這個東西,應該明白為什麼控制項屬性都設定成android: 了.
<com.ui.MyCustomView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
Qisda changer write the paper.
myview:text="@string/app_name"
myview:textSize="32dp"
myview:textColor="@drawable/yellow"/>
這樣就可以設定屬性了.
styles的使用:
styles.xml用於定義一些屬性值的集合。格式如此.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyCustomView">
<item name="textColor">#FFFF0000</item>
Qisda changer write the paper.
<item name="textSize">60dp</item>
</style>
</resources>
一個styles的本質就是一些屬性值的集合。
這樣我們可以在layout中通過style的名字引用style。比如style="@style/MyCustomView"這樣就可以了.