自定义的组件xml属性

来源:互联网 发布:大型企业网络架构 编辑:程序博客网 时间:2024/05/22 06:07

对于自定义的组件,不仅可以利用view自带的xml属性进行布局控制还可以通过自定义xml属性的方式实现对view的控制。

一般写xml属性时android:****的格式,其中的android是命名空间,关于什么是命名空间,这不是本文讨论的范围。一般来说,在xml文件的根部我们都会加上xmlns:android="http://schemas.android.com/apk/res/android",这其实是android定义好的命名空间。因此如果直接在xml文件里写 myxmlns:hello="hello" 那么编译器就会报错,首先把myxmlns当做一个命名空间了,而该命名空间是不存在的,所以会报错。解决办法是首先在view树的根部声明命名空间。

如:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:myxmlns="http://schemas.android.com/apk/res/com.test.xml"android:id="@+id/main"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" />


这里的红色字体部分是我声明的命名空间。当用自定义命名空间时一般的格式为:http://schemas.android.com/apk/res/ “ + ” 应用的包名( 注意,这里应用的包名是:com.test.xml )

当定义完命名空间后,编译器仍会报错,这是由于没有为命名空间配置属性,也就是说该空间内的取值现在是不确定的。
解决办法如下:

在values文件加下新建xml文件进行如下配置:

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="MyView">        <attr name="text" format="string" />    </declare-styleable></resources>



这里的 declare-styleable name="MyView" 是为了获取我们在xml中自定义配置属性的值而设置的一个标志符

而后就可以在xml里面使用该属性了:

如:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:myxmlns="http://schemas.android.com/apk/res/com.test.xml"    android:id="@+id/main"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" ><com.test.xml.MyView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:id="@+id/my_view"    myxmlns:text="hello_world!"></com.test.xml.MyView> </LinearLayout>



原创粉丝点击