8

I have a pretty standard NavigationView. When i use a static layout in the header like below it works perfect.

<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 thah i can change it when user logged in etc... So i tried to use a fragment 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 the headerLayout so i can handle all my logic in the fragment's java file. Or what is the right solution to handle this problem.

Murat Erdogan
  • 798
  • 2
  • 10
  • 21
  • checkout my answer here... http://stackoverflow.com/a/30660069/3544839 ..here i have used TextView as a root while you can use any viewgroup and once you get object of viewgroup you can easily customize it .. – Moinkhan Jul 24 '15 at 04:30

2 Answers2

13

You can do that in code by inflating custom layout and set it's header for navigation view.

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 don't need to set app:headerLayout in xml.

Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61
Sabeeh
  • 1,478
  • 15
  • 15
12

You could call the header declared on xml like this:

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

And then get the views like this:

TextView text = (TextView) header.findViewById(R.id.text);
NueK
  • 121
  • 1
  • 3