Are Android View id supposed to be unique?

前端 未结 3 994
慢半拍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.

    0 讨论(0)
  • 2020-12-18 18:30

    You do a convertView.findViewById(..).

    If all the views need to have a unique id, how does changing the content of View in the getView not result in haphazard behavior ?

    This is because you create an instance of the view by inflating it. In this instance the ids need to be unique. Otherwise you will probably get a ClassCastException (If two different type of views share the same Id).

    It would be impossible to maintain a ListView where every row would have to have unique identifiers for all its views.

    So, what this means is I can not inflate two Fragment in an Activity by using the same layout. This will result in an exception. Both are inflated by the same Activity, hence belong to the same instance. The ids will conflic

    No, fragments work in a different way. You have to return an inflated view in the fragments onCreateView() method. So each fragment has to inflate the view, which results in having 2 separate view objects.

    0 讨论(0)
  • 2020-12-18 18:54

    Why you are using android:id="text"? You should use android:id="@+id/text" or android:id="@id/text" depending on what way you'll choose. Moreover, getView is relative to the item position on scrolled or not ListView

    0 讨论(0)
提交回复
热议问题