Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Android Lists and Adapters (2015) Lists with RecyclerViews Custom Adapters and ViewHolder in RecyclerViews

Same ID is different XML layouts! Need Explanation!

When we do this : mTimeLabel = (TextView) itemView.findViewById(R.id.timeLabel);

How does the IDE know that we are looking for timeLabel inside hourly_list_item.xml and not daily_list_item.xml ?

i am confused by this because we haven't yet specified anything to the adapter about the layout .

1 Answer

Stian Petersen
Stian Petersen
2,421 Points

When the adapter named HourAdapter is created it calls the method HourViewHolder onCreateViewHolder. This inflates a view with R.layout.hourly_list_item as the layout in this code: View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hourly_list_item, parent, false);

This view is then passed to HourViewHolder in this code: HourViewHolder viewHolder = new HourViewHolder(view);

Your question refers to the code in the class named HourViewHolder. When the HourViewHolder gets called it passes in the view from HourAdapter with the layout "R.layout.hourly_list_item". The code looks like this:
public HourViewHolder(View itemView)

This view from AdapterView passed in as itemView and is referenced to find the correct label by itemView.findViewById(R.id.timeLabel);

In short: itemView in itemView.findViewById(R.id.timeLabel); points to the correct layout.

For further reference this code can be found in the Android Lists and Adapters course and the source code can be found in the HourAdapter.java here: http://treehouse-code-samples.s3.amazonaws.com/Android/ListsAndAdapters/StormyLists_s6v1.zip