在Android布局XML文件中,"?android:"和"@android:"有什么区别?

44

"?android:"和"@android:"在Android布局xml文件中有什么区别?它们似乎是重用Android SDK资源的可互换方式。

我发现的唯一区别如下所示。

在这里,TextView的右边缘与ImageButton的左边缘对齐。

 <RelativeLayout
    android:id="@id/header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#888888">
    <TextView
        android:id="@android:id/text1"
        android:layout_alignParentLeft="true"
        android:text="blah blah"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@android:id/button1" />
    <ImageButton
        android:id="@android:id/button1"
        android:layout_alignParentRight="true"
        style="@style/PlusButton" />
</RelativeLayout>

然而,在这里,TextView的右边缘与RelativeLayout的右边缘对齐。TextView会覆盖ImageButton。

<RelativeLayout
    android:id="@id/header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#888888">
    <TextView
        android:id="@android:id/text1"
        android:layout_alignParentLeft="true"
        android:text="blah blah"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="?android:id/button1" />
    <ImageButton
        android:id="?android:id/button1"
        android:layout_alignParentRight="true"
        style="@style/PlusButton" />
</RelativeLayout>

这两种布局之间唯一的区别是使用了@android和?android。它们都可以编译通过,没有错误。

非常感谢。


1个回答

36

在ID前加上问号表示您希望访问样式主题中定义的样式属性,而不是硬编码该属性。

请参见此处的“引用样式属性”:accessing-resources


4
更具体地说,“?”符号意味着额外的间接层级。将其视为取消引用主题属性以获取其指向的资源,而不是仅引用该属性本身。您可以在?android:attr/foo中看到这一点。 - adamp
10
我希望这个答案能够有更多的解释。 - CodyBugstein
@Imray,这是一个例子:我从sdk\platforms\android-L\data\res\values中的themes.xml文件中找到了这些样式。`<style name="Theme"> <item name="colorForeground">@android:color/bright_foreground_dark</item><style> <style name="Theme.Light"> <item name="colorForeground">@color/bright_foreground_light</item> </style> <style name="Theme.Holo"> <item name="colorForeground">@android:color/bright_foreground_holo_dark</item> </style>` 这些项在attrs.xml文件中通过<attr name="colorForeground" format="color" />进行引用,该文件位于同一目录下。 - chjarder
它们使用相同的名称,这意味着它们代表相同的资源。因此,当您在这三个主题之间切换时,您正在使用的属性将获取所选主题中指定的项目,并将其用作可绘制项。如果我的答案涉及到可绘制项,我很抱歉,但这是我能提供的最好的例子。 - chjarder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接