0

I was wondering of two possible ways of handling View IDs in Android:

  1. automatically assign an ID to every View you create
  2. assign IDs only when you need them

I can think of some pros and cons of both approaches (more for the first option) but I want to know if I am right.

Edit: I know you don't have to assign IDs to Views, I wanted to know whether I should (for future's development sake)

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Simon
  • 2,643
  • 3
  • 40
  • 61
  • 1
    No, not every view needs an id. You add ids to views when you need to modify properties of that views and you find those views with their ids. Also you can add or remove those views from any other views or layouts programatically or on run time if you wish. If you don't need that view ever don't add id, and adding id for every view is cumbersome and not needed. – Thracian Oct 19 '17 at 20:18

3 Answers3

1

This is really up to you because it doesn't necessarily have any particular effect on efficiency, depending how you automatically add the IDs. My approach is to only assign IDs as you need them. The reason for this is because you only need the ID to reference the view or component in its controller or if you are using RelativeLayout and placing your other views/components based on other components. Otherwise it's extraneous code that doesn't really get used.

sam_c
  • 810
  • 7
  • 25
1

You do not need to assign ID to every View. You assign ID only if you want a reference of a view from Java Code for example you have a TextView in XML and you want to change its text it into something else at runtime then you have to use an id to refer to using the method findViewById().

In android there are also Tags not only ID but tags are mostly used when you want to create Views programmatically and they can be Strings not Integers like ID.

Xenolion
  • 12,035
  • 7
  • 33
  • 48
0

No, you don't need ID for every view only when you want to cast the xml view to java object and use this object in java code