开发者

Android XML layout files and namespace

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" />
  1. Why is the android prefix used instead of ommitting it like xmlns="http... ?
  2. Why is the prefix used only in attributes and not i开发者_开发知识库n elements?


Interesting question! it sure feel a bit weird.

  1. It was a design choice by Google to be as strict as possible on namespace to handle errors at compile time.
  2. 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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜