1

I have a activity_main.xml with a NavigationView like this:

<android.support.design.widget.NavigationView
    android:id="@+id/nav_drawer"
    android:layout_width="320dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:menu="@menu/menu_drawer"
    app:headerLayout="@layout/header"
    app:itemIconTint="@color/colorAccent"
    />

I have a header layout and there is a textview there. I was wondering how I can access that textview? I have code in my main activity which will update that textview but I am unsure how to have access to that textview. The header.xml is not part of an activity.

In my main activity I have this piece of code:

public void checkCurrentUser() {
    ParseUser user = ParseUser.getCurrentUser();
    if (user != null) {
        nameOfCurrentUser.setText(user.getUsername());
    }
}

which will update that textview with the current user's username

Sheila Grant
  • 65
  • 1
  • 8
  • See this: [http://stackoverflow.com/questions/33161345/android-support-v23-1-0-update-breaks-navigationview-get-find-header](http://stackoverflow.com/questions/33161345/android-support-v23-1-0-update-breaks-navigationview-get-find-header) – hanswim Jan 04 '16 at 10:34

2 Answers2

3

You have to take the view object and find the element,

Java

 View headerLayout = navigationView.getHeaderView(0);
    useremail = (TextView) headerLayout.findViewById(R.id.tv_useremail);

XML

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_home"
        app:menu="@menu/activity_home_drawer" />
Nagendra Badiganti
  • 2,099
  • 2
  • 22
  • 30
  • To reliably update a `TextView` in a navigation drawer header, use this code in the [`ActionBarDrawerToggle.onDrawerOpened()`](https://developer.android.com/reference/android/support/v4/app/ActionBarDrawerToggle.html#onDrawerOpened(android.view.View)) method. See: https://stackoverflow.com/a/35952939/1657502. – Antônio Medeiros Aug 04 '18 at 23:47
0

header is called by xml. so u can simply use:

TextView nameOfCurrentUser = (TextView) findViewById(R.id.YOURTEXTVIEWINHEADER);nameOfCurrentUser.setText(user.getUsername());
Remees M Syde
  • 2,564
  • 1
  • 19
  • 42
Eboo
  • 47
  • 4