Binil Surendran Binil Surendran - 4 months ago 11
Android Question

Android: Navigation Drawer Header Text View is not setting Programaticaly

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 by programtically.

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

Can any one please help me

Answer

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");