打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Android之xml文档中的命名空间

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

那么我就可以在需要使用我自己定义属性的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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

当然,我们也可以找到使用最多的包名xmlns:android=”http://schemas.android.com/apk/res/android”,android包在android.jar包中,其中在android包中有个R类,该文件是系统自动生成的,在R类中有个attr类,其中保存了我们需要使用的各种属性的id。
总结,定义命名空间的作用就是为了让不同空间中的具有相同名字的属性值可以使用,不会造成冲突,让系统崩溃。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
8.2 属性资源与Android命名空间 - 51CTO.COM
xmlns:android作用以及自定义布局属性
TypedArray和attrs.xml
eclipse Camera app
对Android Drawable Resources的研究
Animation 动画详解(一)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服