Are Android View id supposed to be unique?

前端 未结 3 1005
慢半拍i
慢半拍i 2020-12-18 18:17

Ok so something that I am confused with is whether Android ids need to be unique or not. Here is why the confusion arises:
Let\'s just say there is an Activity

3条回答
  •  既然无缘
    2020-12-18 18:29

    In documentation You may read

    An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which may often be the entire tree, so it's best to be completely unique when possible).

    It means there will be no exceptions if You use same id for all Your views but obviously layout will get useless then.

    FindViewById works simply by traversing a tree until it finds first element with searched id and returns it (or null if doesn't find). If You had few elements with same id in tree You will always get same element, the one that is first in tree.

    You may have plenty of fragments inflated with same layout just like you have ListView with each element having same layout, that is because inflater doesn't care about id values. It simply reads XML file and create a tree with correct view objects nothing more.

提交回复
热议问题