NavigationView how to handle dynamic header content

I have a pretty standard navigation menu. When I use a static layout in the header as shown below, it works fine.

<android.support.design.widget.NavigationView android:id="@+id/nav_view" android:layout_height="match_parent" android:layout_width="wrap_content" android:layout_gravity="start" android:fitsSystemWindows="true" app:headerLayout="@layout/nav_header" app:menu="@menu/drawer_view"/> 

But I want to have a dynamic header, so I can change it when the user is logged in, etc. So I tried using a snippet instead of nav_header.xml

 <android.support.design.widget.NavigationView android:id="@+id/nav_view" android:layout_height="match_parent" android:layout_width="wrap_content" android:layout_gravity="start" android:fitsSystemWindows="true" app:headerLayout="@layout/fragment_header" app:menu="@menu/drawer_view"/> 

Can I use a fragment in headerLayout, so I can process all my logic in a java fragment file. Or what is the right solution to solve this problem.

+6
source share
2 answers

You can do this in code by inflating a custom layout and setting its title for navigation.

 NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView); View nav_header = LayoutInflater.from(this).inflate(R.layout.nav_header, null); ((TextView) nav_header.findViewById(R.id.name)).setText("UserName"); navigationView.addHeaderView(nav_header); 

You do not need to install app:headerLayout in xml.

+11
source

You can call the header declared in xml as follows:

 NavigationView navigationView= (NavigationView) findViewById (R.id.navigationView); View header = navigationView.getHeaderView(0); 

And then we get the following types:

 TextView text = (TextView) header.findViewById(R.id.text); 
+10
source

All Articles