Android中,我们所需要使用的大部分资源都是通过xml文件定义的,并且还需要在xml文件中定义相关控件的属性。但是在定义控件属性时,我们必须在前面加上android命名空间。在xml文档开头我们会有这么一行代码:xmlns:android=”http://schemas.android.com/apk/res/android” 。其中:
- xmlns全称是XML namespaces,就是用来定义xml命名空间的。
- android是为该命名空间起的别名,我们如果要使用该命名空间中的属性,就要使用加上这个命名空间名字,因为我们不能保证在所有的命名空间中属性名字不一样。若是没有命名空间的限制,而我们所使用的不同属性的属性名又一样了,那么就会导致系统报错,因为系统不知道使用哪个属性来配置你的控件。
- “http://schemas.android.com/apk/res/android“是该命名空间,命名空间的定义前缀是“http:/schemas.android.com/apk/res/”,在这个前缀的后面加上相应的包名,就可以使用对应包下的资源了。
例子说明:我在我的com.grayboy.demotest包下的values文件夹下创建一个attrs.xml资源文件。其中假如我们自己定义的一些属性:
<pre name="code" class="html"><resources>
<declare-styleable name="LabelView">
<attr name="mytest" format="color" />
<attr name="myname" format="string" />
</declare-styleable>
</resources>
那么我就可以在需要使用我自己定义属性的xml文件中定义我的命名空间,然后使用自定义的属性:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myns="http://schemas.android.com/apk/res/com.grayboy.demotest" //使用我自己的包定义命名空间
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
myns:myname="@string/myname" //使用我自己定义的属性
/>
</LinearLayout>
当然,我们也可以找到使用最多的包名xmlns:android=”http://schemas.android.com/apk/res/android”,android包在android.jar包中,其中在android包中有个R类,该文件是系统自动生成的,在R类中有个attr类,其中保存了我们需要使用的各种属性的id。
总结,定义命名空间的作用就是为了让不同空间中的具有相同名字的属性值可以使用,不会造成冲突,让系统崩溃。