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

标签 android

Possible Duplicate:
What is different between @+id/android:list and @id/android:list ??

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

代码示例:

<Button
android:id ="@id/add_button"
/>
<Button
android:id ="@+id/remove_button"
/>

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

最佳答案

您必须在 XML 文件中 ID 的第一次出现时使用 @+ 表示法。第二次和以后的时间你可以——也应该——去掉 + 符号。这将有助于发现拼写错误。

例如,假设您有一个 RelativeLayout。在 RelativeLayout 中有一个 TextView,其 android:id@+id/label。稍后在布局 XML 文件中,您希望从另一个文件中引用该 TextView 以进行定位(例如,用于 android:layout_below)。

如果您在编译时输入了 android:layout_below="@+id/labbel"(注意错字),这将被认为是可以的。但是,在运行时,事情将不起作用,从小部件定位不正确到彻底崩溃,具体取决于 Android 版本。

如果您输入了 android:layout_below="@id/labbel"(注意错字缺少的 + 符号),那么你会得到一个编译错误。


更新

由于第一次不够清楚,显然,让我们再试一次。

<?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>

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

您可以在所有这些上使用 + 符号,但是如果您打错字,编译器将无法捕捉到问题。

+ 符号有效地表明“分配一个新 ID”。没有 + 符号表示“使用以前分配的 ID,如果没有这样的 ID,则在编译时失败”。

关于android - android中@id/和@+id/有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5731414/

相关文章:

android - 如何显示街景预览

Android Studio v1.3 检查未经检查的权限使用情况

通过键盘缩小 Android Spinner

java - 更深入地了解 Realm 的工作原理?

android - 如何为 TextView 中的单个字符设置动画?

java - 无法在 Java Android 中按单个 HashMap 对象字段对 ArrayList<HashMap<String, Object>> 进行排序

android - 无法在 Kotlin 映射列表

java - OpenGL形状绘图绕y轴反转?

java - Android - 错误的第一个参数类型和 ' android.supportv4.app.Fragment'

java - 将 xml 转换为 java 对象有困难