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);
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
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");
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With