2

以下是我从站点选择的代码。这种模式用在很多类似的代码中。

<Button
    android:id="@+id/btnButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button 1"/>

<Button
    android:id="@+id/btnButton2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button 2"
    android:layout_toRightOf="@+id/btnButton1"/> <!-- Why use @+id again and not just @id/btnButton1  -->

AFAIK + 号是将 id 添加到资源 id 列表的捷径。@+id/foo 表示您正在应用程序的命名空间中创建一个名为 foo 的 id。您可以使用@id/foo 引用它。

那么为什么不使用android:layout_toRightOf="@id/btnButton1而不是android:layout_toRightOf="@+id/btnButton1因为资源已经用 id 定义了呢?

4

5 回答 5

3

@+id在引用已经声明的标识符时,使用标识符声明语法当然是一种常见的模式。

优点:

  • 您可以自由地重新排序 XML 中的元素,而无需更改标识符声明和引用的顺序。

缺点:

  • 尝试引用现有标识符时,不会自动检测标识符名称中的拼写错误。
于 2013-11-11T11:21:37.390 回答
1

好吧,一旦您需要使用锚点layout_toRightOf,这就是您需要提供 id 的原因。其次,您可以省略+. +保留添加到R.id类,但由于它仅包含静态最终字段,因此它的值被分配一次。

于 2013-11-11T11:12:10.053 回答
1

您应该android:layout_toRightOf="@id/btnButton1"/>在引用另一个视图时使用,无需使用 + 号

于 2013-11-11T11:13:49.157 回答
1

您需要使用这样的代码来定义视图,只需提供带有“+”号的 id:

android:id="@+id/btnButton1"

定义后,它将出现在 R.id 类中。然后你可以在调用它时只使用一个简单的@id:

android:id="@id/btnButton1"

因此,当您引用此视图时,您不再需要“+”:

<Button
    android:id="@+id/btnButton2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button 2"
    android:layout_toRightOf="@id/btnButton1"/>
于 2013-11-11T11:15:01.177 回答
0

最佳做法是为@+id/您的 ID 的第一次出现添加,并且在您以后想要引用它时使用@id/

如果您后来更改了 XML 文件组件的排列并且忘记+在您的 ID 的第一次出现时添加符号,则应用程序将崩溃,因为您试图引用R.java尚未在文件中声明的 ID。

这就是为什么建议使用@+id/always 来避免这样的问题。

我希望这可以帮助您了解它是如何工作的

于 2015-04-01T06:54:07.390 回答