Android的XML布局文件和名称空间布局、名称、文件、空间

2023-09-05 05:29:04 作者:无情帝王

Android的布局的XML定义的根元素中声明该命名空间:

 的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
 

的元素的示例:

 < TextView的Andr​​oid的:layout_width =FILL_PARENT机器人:layout_height =WRAP_CONTENT/>
 

为什么机器人 preFIX使用ommitting像,而不是的xmlns =HTTP ... ? 为什么只在属性,而不是在要素使用preFIX? 解决方案

有趣的问题!它肯定觉得有点不可思议。

这是一个设计选择由谷歌要尽可能严格的命名空间在编译时处理错误。 的preFIX上没有的元素使用,因为论文重新presenting Java类: com.android.widget.TextView com.android.widget。* 总是可以被截断)。这个类的java的命名空间会被自动地解决在编译时,所以XML命名空间重新presenting标准Java命名空间不欢迎你。但属性可以被映射到任何元素的继承java类的。因此,对属性的命名空间,允许继承。 Android Studio 基本知识

这是做这样主要是因为布局描述Java对象和谷歌这是使用XML命名空间机制与Java对象映射布局帮助。因此,有在Java世界的命名空间和XML命名空间的世界之间的冲突。 这也让我们开发商子类的元素,而无需担心平台的下一个版本将可能添加属性具有相同的名称添加自己的属性。

看到两个答复,这篇博客被戴安娜Hackborn 的,一个知名的android工程师在谷歌工作:的http://www.elharo.com/blog/software-development/xml/2008/09/16/android-xml-weirdness/

Android layouts are defined in XML with this namespace declared in the root element:

xmlns:android="http://schemas.android.com/apk/res/android"

Example of an element:

<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" />

Why is the android prefix used instead of ommitting it like xmlns="http... ? Why is the prefix used only in attributes and not in elements?

解决方案

Interesting question! it sure feel a bit weird.

It was a design choice by Google to be as strict as possible on namespace to handle errors at compile time. The prefix is not used on elements because theses are representing Java classes: com.android.widget.TextView (com.android.widget.* can always be truncated). The java namespace of this class will be automagically resolved at compile time, so an xml namespace representing a fully qualified java namespace is not welcome here. But attributes can be mapped to any of the inherited java classes of the Element. Hence the namespace on attributes to allow inheritance.

This is done like this mainly because the layout describes Java objects and Google here is using the XML namespace mechanism to help in mapping your Layout with Java objects. So there are collisions between the Java namespace world and XML namespace world. It also allow us developers to subclass elements, add our own attributes without worrying that the next version of the platform will maybe add an attribute with the same name.

See the two replies to this blog post by Dianne Hackborn, a well-known android engineer working at google: http://www.elharo.com/blog/software-development/xml/2008/09/16/android-xml-weirdness/