Skip to content

Instantly share code, notes, and snippets.

@Mercandj
Last active February 2, 2022 23:05
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 Mercandj/b236a57f341d0ff1c9e88958cdb5dc3e to your computer and use it in GitHub Desktop.
Save Mercandj/b236a57f341d0ff1c9e88958cdb5dc3e to your computer and use it in GitHub Desktop.

Android view: Layout IDs creation

Issue:

Here a ConstraintLayout in a layout containing 2 views:

<androidx.constraintlayout.widget.ConstraintLayout>

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

    <View
       android:id="@+id/main_activity_end_view"
       ...
       app:layout_constraintStart_toEndOf="@+id/main_activity_start_view" />

</androidx.constraintlayout.widget.ConstraintLayout>

In code, getting the "start_view" reference will be:

findViewById(R.id.main_activity_start_view)

Your cursor is on main_activity_start_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!

image

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

Developers are expecting to jump to the id definition so to the xml block where the view is, not the reference.

Solution:

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 another view, whose id is already in R.java.

The layout should reference the main_activity_start_view with a @id/

<View
   android:id="@+id/main_activity_end_view"
   ...
   app:layout_constraintStart_toEndOf="@id/main_activity_start_view" />

Reasons:

  • Wrong use of @+id via the layout text editor
  • Creating the ConstraintLayout via the AndroidStudio ViewEditor will automatically create ids and may add @+id/ instead of @id/

Adapted from https://gist.github.com/bowserf/87c5be8b98df93dd733edde4f3568723. Thanks @Bowserf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment