android系统原理解读

Android xmlns

2016-01-13  本文已影响1168人  InSight_Suen

XML Namespace

xmlns

xmlns是XML语言中表示Namespace位置的标签,被定义在元素的开始标签中时。
标准语法为:
<element xmlns:prefix="http://Namespace-name-URI">
其中分为两部分:

在Android xml布局文件头部的
xmlns:android="http://schemas.android.com/apk/res/android"
即Android API的Namespace。

xmlns:app

在引用Library的第三方View时,我们需要在XML布局文件头部添加
xmlns:app="http://schemas.android.com/apk/res-auto"
或者
xmlns:app="http://schemas.android.com/apk/res/包名"

在ADT 17.0.0(2012.3)更新中,添加了对Library自定义View的自定义attribute的支持。
通过使用http://schemas.android.com/apk/res-auto标识XML NameSpace,而不是以往的包名。

为什么要使用xmlns:app

在xml布局文件中,我们需要标识
xmlns:android="http://schemas.android.com/apk/res/android"
指定我们所用到的attribute。但由于API升级,有些新添加或者更新的attribute对低版本API无法支持或者效果不一致。
xmlns:app其实并不仅限于Library,而是针对整个App:无论是你引用的Library中的attribute,还是你自定义的全局attribute都有效。
因此,我我们引用的appcompat-v7Library使用和xmlns:android相同的自定义attribute(例如:android:showAsAction,添加于API11)。显然,使用android:showAsAction的话,低版本API设备是无法支持的,而使用app:showAsAction则能都支持所有API版本。
通过使用app:showAsAction,我们便使用到了appcompat-v7的自定义attribute,其定义在appcompat-v7res/values/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    ...

    <!-- Base attributes that are available to all Item objects. -->
    <declare-styleable name="MenuItem">

        ...

        <!-- How this item should display in the Action Bar, if present. -->
        <attr name="showAsAction">
            <!-- Never show this item in an action bar, show it in the overflow menu instead.
                 Mutually exclusive with "ifRoom" and "always". -->
            <flag name="never" value="0" />
            <!-- Show this item in an action bar if there is room for it as determined
                 by the system. Favor this option over "always" where possible.
                 Mutually exclusive with "never" and "always". -->
            <flag name="ifRoom" value="1" />
            <!-- Always show this item in an actionbar, even if it would override
                 the system's limits of how much stuff to put there. This may make
                 your action bar look bad on some screens. In most cases you should
                 use "ifRoom" instead. Mutually exclusive with "ifRoom" and "never". -->
            <flag name="always" value="2" />
            <!-- When this item is shown as an action in the action bar, show a text
                 label with it even if it has an icon representation. -->
            <flag name="withText" value="4" />
            <!-- This item's action view collapses to a normal menu
                 item. When expanded, the action view takes over a
                 larger segment of its container. -->
            <flag name="collapseActionView" value="8" />
        </attr>

        ...

    </declare-styleable>
    
    ...

</resources>
上一篇下一篇

猜你喜欢

热点阅读