Skip to content

Instantly share code, notes, and snippets.

@bowserf
Last active January 27, 2022 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bowserf/87c5be8b98df93dd733edde4f3568723 to your computer and use it in GitHub Desktop.
Save bowserf/87c5be8b98df93dd733edde4f3568723 to your computer and use it in GitHub Desktop.
[Android] A good usage of "@+id" and "@id" in a layout file

A good usage of @+id and @id

Problem:

Imagine you have a ConstraintLayout. It contains 2 views with one at the right of the other:

<androidx.constraintlayout.widget.ConstraintLayout ...>

    <View android:id="@+id/left_view" ... />

    <View android:id="@+id/right_view"
        ...
        app:layout_constraintStart_toEndOf="@+id/left_view" />

</androidx.constraintlayout.widget.ConstraintLayout>

Now you are in your kotlin/java code, you have the following code:

val leftView = findViewById<View>(R.id.left_view)

Your cursor is on left_view and you click on cmd + B (Mac OS) to jump to your view inside the layout and BOOM! Android Studio asks you to choose toward which view id creation you want to go!

Screenshot 2020-08-25 at 19 33 11

But which one is the one set in the android:id of the view?

When to use @+id

We use it when we want to create a new identifier for a view, it means when we write android:id="@+id/{VIEW_ID}".

The + sign permits to create a new entry in the R.java.

When to use @id

When we want to do a reference to a view, whose id already exists in R.java.

In our previous example, we should use @id to reference the left_view in order to position view with id right_view.

<View android:id="@+id/right_view"
    ...
    app:layout_constraintStart_toEndOf="@id/left_view"/> <!-- No @+id here -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment