Reputation: 7634
I know the difference between @+id
and @id
(see this accepted answer). However, I always get the feeling that I'm doing the job of the AAPT compiler when I write the '+' in @+id
.
Is there a reason the resource compiler cannot infer by itself if an identifier must be created or just reused? An underlying hashtable structure would do the job: every resource with the same id go into the same bucket, and if the key does not exist, just create it.
Upvotes: 8
Views: 346
Reputation: 7108
I could imagine it is to help the programmer.
If you did not need the @+id construction then all @id references/constructions would be valid, then it would be difficult to track down an error, as the compiler would not fail on incorrect references (as it would simply construct the typo id).
Put differently, all id reference errors would have to be discovered at runtime.
Edit:
Just noticed the similar answer by Piovezan, regarding your comment:
Maybe, but the result is that many devs use @+id everywhere, since there is no error if the id is already defined, and everything works just fine. That means the compiler tests if the id already exist, but not if it does not exist, that's crazy
Then those developers are misusing the @+id construction imo.
It is still much better to have the option to distinguish between @+id and @id, since (for those who does not misuse the @+id) the compiler has a chance of giving a compile time error on wrong references.
Edit2
And to address the comment:
That's the link I gave in the first sentence. It explains the difference but does not answer why the '+' cannot be automatically infered by AAPT
I believe it can, it just does not due to the argumentation above (i believe).
Upvotes: 1
Reputation: 3223
Probably the compiler would not be able to differentiate between a 'right' and a 'wrong' id. If it finds a new id (i.e. one that is not in the underlying hashtable), it would always assume it to be a right, new id. It would not be able to differentiate between an actual new id and a mistyped id.
Upvotes: 1
Reputation: 4104
with @+id you are adding id to R.java which allows you to reference it from Java classes while with @id you are not. You can use @id only if specific id is already created and you are referencing it in another view e.g. android:layout_below="@id/some_id"
Upvotes: 0