Search code examples
androidtagsunique

android studio: unique identifier for each element


I have an android application where not all elements have unique ID's. For example, two TextViews are each called "itemButton" and are on the same screen. I want to give every element a unique identifier by setting a tag on each element.

My current solution is to iterate through every element in the application and set the tag for each element. This is a very expensive solution because I have many elements. Is there another property you know of that would help identify an element other than setting a unique tag for each element?


Solution

  • View IDs have no special requirement that they be unique. However, you will run into difficulties if you use non-unique IDs on a single screen.

    The two most common issues you will face if you use non-unique IDs are (1) failure of the system to automatically save instance state for the view and (2) findViewById() returning the "wrong" view.

    Activity.findViewById() will search the view hierarchy for the first view it finds with the matching ID. If you have two views in your hierarchy with the same ID, that means you won't be able to find the second one using this method. However, you can use View.findViewById() instead.

    View.findViewById() will search the view hierarchy starting from the view you're invoking the method on, which means that you can differentiate between two views with the same ID as long as they have different parents.

    In your case, I suspect you can do something like the following:

    View parentOne = findViewById(R.id.parentOne);
    View childOne = parentOne.findViewById(R.id.someIdBeingReused);
    
    View parentTwo = findViewById(R.id.parentTwo);
    View childTwo = parentTwo.findViewById(R.id.someIdBeingReused);