NavigationView get/find header layout

khusrav picture khusrav · Oct 18, 2015 · Viewed 96.7k times · Source

In my NavigationView I have a header layout with id 'viewId' with active buttons. To setup those buttons, I do the following in activity's onPostCreate:

final View panel = findViewById(R.id.viewId);
panel.setOnClickListener(new View.OnClickListener() {
... setup goes here ...
});

With new version android support library, (23.1.0), the view can't be found, it returns null. With previous versions it worked well. Is it a bug or am I using this feature wrong? If so, how to access header layout and add behavior to it?

Answer

ianhanniballake picture ianhanniballake · Oct 18, 2015

Version 23.1.0 switches NavigationView to using a RecyclerView (rather than the previous ListView) and the header is added as one of those elements. This means it is not instantly available to call findViewById() - a layout pass is needed before it is attached to the NavigationView.

For version 23.1.1 of the Support Library, you can now get a reference to the header view using getHeaderView():

View headerLayout = navigationView.getHeaderView(0); // 0-index header

This has the advantage of working on headers added via XML and via code.

If you are still using 23.1.0, as per the related bug, you can inflate the header in code and use findViewById() on that:

View headerLayout = 
    navigationView.inflateHeaderView(R.layout.navigation_header);
panel = headerLayout.findViewById(R.id.viewId);
// panel won't be null

Until you move to 23.1.1.