I know I can use include/merge to include an XML file in another XML file. If the included layout contains children and you include several instances of this in the root view, how do you find the ID of each child instance?
For example if the included layout contains a listview, and you include 3 instances of this layout in the root layout, how do you find and reference the 3 listview children?
UPDATE:
For folks reading this thread: There is actually a much better solution that I have found, and in retrospect its quite obvious. The problem with getChildAt() is that if you add new views or re-arrange things, this code will either crash or not work since the index of the children has changed, and the class types may not even match anymore. So not very maintainable. It turns out that findViewById() works fine if you just drill down a bit further into the layout and if you give each of the includes an ID. So for example, suppose you have 3 includes in a layout, with ID names “list_container1”, “list_container2” and “list_container3”. Each of these includes the same list view XML with the same ID name. Now instead of trying to find your lists from the root layout, which won’t work, find the containers first, then find the lists like this:
myRootLayout = (LinearLayout) findViewById(R.id.root_layout);
container1 = (LinearLayout) myRootLayout.findViewById(R.id.list_container1);
list1 = (ListView) container1.findViewById(R.id.my_list_view);
container2 = (LinearLayout) myRootLayout.findViewById(R.id.list_container2);
list2 = (ListView) container2.findViewById(R.id.my_list_view);
container3 = (LinearLayout) myRootLayout.findViewById(R.id.list_container3);
list3 = (ListView) container3.findViewById(R.id.my_list_view);
In the above example, the layout hiearchy is like this (and could be further simplified):
LinearLayout
<include>
LinearLayout
ListView
<include>
LinearLayout
ListView
<include>
LinearLayout
ListView
You can use your root layout’s
getChildAt(int index)method to go to any child. In factfindViewById()simply uses this andgetChildCount()to loop through all of a layout’s child views until one matches the given id.Example:
The exact index depends on how you have arranged your layout.