Android XML 中的许多标识符都需要在前面添加 @
作为对 XML 中其他位置定义的值的引用。
例如
@drawable/transparent
@color/red
@string/hello_world
但是,id 很奇怪,因为语法不同:
@+id/my_id
显然,对于其他标识符,我们正在引用可能在其他地方定义的资源,而对于 id,我们正在创建标识符。为什么要使用@+
的语法?我很好奇这个语法的真正含义是什么,以及除了 @+id
之外它是否还有其他用途(是否有 @+string
或 @ +颜色
?)。
最佳答案
However, id's are quite odd in that the syntax is different
语法有时不同。
Why though the syntax of @+?
表示我们正在专门创建一个标识符,而@id/...
表示我们正在引用一个应该已经在此资源文件中先前定义的标识符。
例如:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/entry"
android:layout_alignParentLeft="true"
android:text="@string/url"/>
<EditText
android:id="@id/entry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@id/label"
android:inputType="text"/>
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@id/entry"
android:layout_below="@id/entry"
android:text="@string/ok"/>
<Button
android:id="@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/ok"
android:layout_toLeftOf="@id/ok"
android:text="@string/cancel"/>
</RelativeLayout>
我对 label
和 entry
标识符的第二次引用使用 @id/
,表明该标识符应该已经在前面定义过文件。
早在拖放 GUI 构建器等出现之前,这将有助于在编译时检测 ID 不匹配情况。例如,如果我输入 @id/ernty
而不是 @id/entry
,我会收到编译错误,因为没有 @+id/ernty
在文件中存在于它之前。
if there are other uses for it besides merely @+id
我不知道。
关于java - 当我在 Android 中输入 @+id 时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25413235/