Funwise Funwise - 1 month ago 8
Java Question

How to change Navigation Drawer's header layout background color dynamically?

As you know, android studio has a Navigation Drawer Activity which creates a bunch of layouts by itself inside the layout folder.

enter image description here

nav_header_main.xml
is the layout which contains the components of the NavigationView header. I have highlighted it in the above picture and It has the following code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/sideNavLayout"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android.studio@android.com" />

</LinearLayout>


I want to change the background of the highlighted portion in the above picture from the
MainActivity.java
like so:

LinearLayout sideNavLayout;
sideNavLayout = (LinearLayout) findViewById(R.id.sideNavLayout);
sideNavLayout.setBackgroundResource(R.drawable.my_side_nav_bar);


But where ever I use it I get the error:


java.lang.NullPointerException


Can anyone help me in this regard?

Answer

You should inflate the navview header layout to access the children

NavigationView navView= (NavigationView) findViewById(R.id.nav_view);
View header=navView.getHeaderView(0);
LinearLayout sideNavLayout = (LinearLayout)header.findViewById(R.id.sideNavLayout);
sideNavLayout.setBackgroundResource(R.drawable.my_side_nav_bar);