0

So I have a Navigation Drawer, the xml code for the drawer is as follows. The xml file is named navigation_drawer_header.

<?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="180dp"
android:background="@drawable/wallpaper">

<ImageView
    android:layout_margin="40dp"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="@drawable/company_logo"
    android:id="@+id/navigation_header_logo"/>

</RelativeLayout>

Then my activity main calls the Nav Drawer in

<android.support.design.widget.NavigationView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/navigation_view"
    android:layout_gravity="start"
    app:headerLayout="@layout/navigation_drawer_header"
    app:menu="@menu/drawer_menu">
</android.support.design.widget.NavigationView>

You'll notice that the nav drawer is implemented in the line

app:headerLayout="@layout/navigation_drawer_header"

So I want to change the background of the ImageView inside of my Nav Drawer, the one with id of navigation_header_logo. I have tried using

ImageView navImg = (ImageView) findViewById(R.id.navigation_header_logo);
navImg.setBackgroundResource(R.drawable.new_logo);

but that seems to crash the app. Can someone help?

dckuehn
  • 2,427
  • 3
  • 27
  • 37
Luke Wang
  • 143
  • 2
  • 9
  • What is the crash? Are you properly inflating the view before looking for the view by id? please post a larger code snippet with more context, and any errors you get when it crashes – MrSalmon Jul 14 '16 at 20:21
  • The java code is in an Activity, not a Fragment, so I don't have view to inflate. Which code do you need? – Luke Wang Jul 14 '16 at 20:37
  • You still need to inflate your view. In an activity this is normally with a call to `setContentView` in onCreate. Please post the error you are receiving when it crashes (logcat/stacktrace). Is it a null pointer exception? – MrSalmon Jul 14 '16 at 20:39
  • Oh yeah I have setContentView. as for the error, I looked into the logcat when the app crashed. it does indeed seem to be a null pointer exception. logcat says: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setBackgroundResource(int)' on a null object reference should i post the entire log? – Luke Wang Jul 14 '16 at 20:42
  • I think this should answer your question http://stackoverflow.com/questions/32246360/how-to-get-view-from-drawer-header-layout-with-binding-in-activity . I know you are not using databinding, but the answer is still relevant in getting the header layout – MrSalmon Jul 14 '16 at 21:11
  • Yeah that worked. Thank you so much for your help MrSalmon. – Luke Wang Jul 14 '16 at 21:26

0 Answers0