I am developing an Android app. In my app, I am working with navigation view. I need to change design of header view programmatically according to a situation. But variable of the instance of header view is always throwing null exception. What is wrong with my code?
This is how I set header view in navigation view
<android.support.design.widget.NavigationView
app:itemIconTint="@drawable/drawer_item"
app:itemTextColor="@drawable/drawer_item"
android:id="@+id/left_nv_view"
app:headerLayout="@layout/header_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start" />
This is the layout of my header view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/header_view"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
This is how I instantiate header view and make changes to it in activity
//I initialized navigation drawer and navigation view first
headerView = (LinearLayout)findViewById(R.id.header_view);
headerView.setOrientation(LinearLayout.VERTICAL);
But it always throwing null pointer exception. How can I fix my code?
A NavigationView
takes some time to get its header View
s inflated and laid out. Often, this will not be complete until after onCreate()
has finished, but you can force it to happen immediately by using the NavigationView#getHeaderView()
method.
After the headers have been successfully loaded, you would then be able to find them in the Activity
's View
hierarchy, and your call to findViewById()
wouldn't return null.