简体   繁体   中英

How does findViewById works on a multi hierarchy tree with many IDs from a Custom View?

I have a quite complex View with many hierarchies. Within that, I have a CustomView called ExpandableText, in which I have a RelativeLayout and a TextView inside it with "expandable_text" as ID.

In my main view, I'm creating multiple instances of ExpandableView with the code:

<include layout="@layout/expandable_text"
         android:id="@+id/expandable1"
/>
<include layout="@layout/expandable_text"
         android:id="@+id/expandable2"
/>
<include layout="@layout/expandable_text"
         android:id="@+id/expandable3"
/>

These ExpandableViews are within a LinearLayout. At some point I got the reference to the LinearLayout, and wanted to access all three expandable_texts within my custom view.

In this case, how does findViewById() work?

I mean, my hierarchy is basically:

ParentViews... > LinearLayout > 3 ExpandableViews > RelativeLayout > TextView

where these TextViews have the same ID, and each ExpandableView has a different ID.

I looked on google and couldn't find much of how this DOM structure works. From Android Developer :

View IDs need not be unique throughout the tree, but it is good practice to ensure that they are at least unique within the part of the tree you are searching.

And on this topic someone said:

It's not random at all. findViewById() is a depth-first search algorithm; it will return the first view of the specified id it can find.

Is it correct? I mean, I basically created this topic out of curiosity of how the Android "DOM traversing" works, and I'd appreciate if someone could clarify that.

Is it correct?

Yes, that's how it will work. It would find the TextView within the first expandable view. To narrow it down, in this case, what you would want to do is first find the unique expandable row, and from that view, look for the TextView . For instance, assuming your TextView 's ID is my_textview and you want to find that view within the second row:

View expandedRow2 = findViewByid(R.id.expandable2);
TextView textView2 = (TextView) expandedRow2.findViewById(R.id.my_textview);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM