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的本质就是一些属性值的集合。
那这个属性从哪来的呢? 需要设置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.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"这样就可以了.