android中的@ id /和@ + id /有什么区别?

haz*_*zem 18 android

可能重复:
@ + id/android:list和@id/android:list之间有什么不同?

有什么区别@id/.. and @+id/..?我不是指@android:id/..和之间的区别 @id/..

代码示例:

<Button
android:id ="@id/add_button"
/>
<Button
android:id ="@+id/remove_button"
/>
Run Code Online (Sandbox Code Playgroud)

id上面两个定义有什么区别?

Com*_*are 39

您必须@+在XML文件中首次出现ID时使用该表示法.第二次以及随后的时间你可以 - 而且应该 - 掉下+标志.这将有助于捕捉拼写错误.

例如,假设你有一个RelativeLayout.你有一个TextViewRelativeLayoutandroid:id@+id/label.稍后在布局XML文件中,您希望TextView从另一个文件中引用它以用于定位目的(例如,for android:layout_below).

如果您输入android:layout_below="@+id/labbel"(请注意拼写错误),在编译时,这将被视为正常.但是,在运行时,事情将无法正常工作,从小部件被错误定位到彻底崩溃,具体取决于Android版本.

如果你输入android:layout_below="@id/labbel"(注意拼写错误丢失的+符号),那么你会得到一个编译错误.


UPDATE

因为我第一次不够清楚,显然,让我们再试一次.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="URL:"
        android:layout_alignBaseline="@+id/entry"
        android:layout_alignParentLeft="true"/>
    <EditText
        android:id="@id/entry"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/label"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/ok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/entry"
        android:layout_alignRight="@id/entry"
        android:text="OK" />
    <Button
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/ok"
        android:layout_alignTop="@id/ok"
        android:text="Cancel" />
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

在上面,你会看到一个RelativeLayout.您会注意到每个ID的第一次出现都会得到+符号.每个ID的第二次和后续出现都没有得到+标志.

您可以+在所有这些上使用该符号,但如果您输入错误,编译器将无法解决问题.

+标志有效地表明"分配新ID".没有+符号状态"使用先前分配的ID,或者如果没有这样的ID则在编译时失败".


Vai*_*ani 6

在Android布局资源XML源文件中:

"@+id/anyId" :添加新ID

"@id/anyId" :引用现有的id

"@id/anyId"只有当"anyId"已经添加到R.java类中时才应该使用"@+id/anyId"