Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Navigation Drawer Header Text View is not setting programmatically

In My activity I have fragment so I am using Navigation Drawer, In the Navigation Drawer I have a header with TextView. I want to update it programmatically.

Header.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="190dp"
android:background="@drawable/background_material"
android:orientation="vertical"
>


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Name Name Name"
    android:textSize="20sp"
    android:textColor="#FFF"
    android:textStyle="bold"
    android:gravity="left"
    android:paddingBottom="4dp"
    android:id="@+id/c"
    android:paddingLeft="10dp"
    android:layout_above="@+id/email"

  />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="+919999999999"
    android:id="@+id/email"
    android:gravity="left"
    android:layout_marginBottom="8dp"
    android:paddingLeft="10dp"
    android:textSize="20sp"
    android:textColor="#fff"
    android:layout_alignParentBottom="true"
    android:layout_alignLeft="@+id/username"
    android:layout_alignStart="@+id/username" />

Am Intializing the naviation view by

  navigationView = (NavigationView) findViewById(R.id.navigation_view);

enter image description here

TextView txt2;
txt2 = (TextView)    navigationView.inflateHeaderView(R.layout.nav_header_main).findViewById(R.id.textView2);
 txt2.setText("wow! It works like a charm");

But getting Null Pointer exception

like image 836
Binil Surendran Avatar asked Jan 15 '16 08:01

Binil Surendran


2 Answers

You should change the code slightly as below.

  //        Set Drawer Header
            NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
            View headerView = LayoutInflater.from(this).inflate(R.layout.header, navigationView, false);
            navigationView.addHeaderView(headerView);
            TextView Name = (TextView) headerView.findViewById(R.id.name);
            Title.setText("Myname");
            TextView Number = (TextView) headerView.findViewById(R.id.number);
            Email.setText("+1234567890");
like image 147
Mr Robot Avatar answered Nov 15 '22 05:11

Mr Robot


Use getHeaderView(0) on your navigation drawer

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

View headerView = navigationView.getHeaderView(0);

//Link Views
navUsername = (TextView) headerView.findViewById(R.id.navUsername);
//Set text here
navUsername.setText("Your text here");
like image 24
Bereket Gobeze Avatar answered Nov 15 '22 04:11

Bereket Gobeze