wholerabbit
wholerabbit

Reputation: 11546

Why does the designer use "@+id" instead of "@id" for constraints?

I've always understood @+id to indicate the creation of a new ID (generally used with android:id), and @id to reference it elsewhere, as explained at length in a popular question here and in the official documentation:

The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android package namespace...

That this is not enforced is a bit odd; you can just use @+id everywhere, multiple times with the same id, and it does not seem to be an error or problem (unless you use the same id with multiple android:id declarations).

When using the graphical designer in Android Studio with constraint layout (it could in fact be with everything, I have not checked), whenever a constraint is added it will declare them like this:

app:layout_constraintTop_toBottomOf="@+id/rlistfrag"

Where rlistfrag is assigned to another element with android:id in the same file -- if it didn't exist already, the designed could not have created the constraint, so there can be no contextual ambiguity.1 According to the docs this amounts to twice declaring "a new resource name that must be created and added to our resources".

It seems the semantics here are not, by omission at least, exactly as described in the docs. Why does the designer do this and what are those omitted semantics?


  1. Or could there? What all this implies to me is that elements may be processed in any order so the point is whenever an id is first encountered it will be created, even if it is not associated with an existing element.

There's a bit in the doc guide on layout resources that confirms the id will only be set the first time:

The plus symbol, +, indicates that this is a new resource ID and the aapt tool will create a new resource integer in the R.java class, if it doesn't already exist.

Which need not mean the elements aren't processed in order.

Upvotes: 5

Views: 316

Answers (1)

dharmik nanavati
dharmik nanavati

Reputation: 21

It is applied in all layout components. whenever you want to mention "id" you have to use "@+id"

Upvotes: 0

Related Questions