2

I have trouble deciding where to set the image of an ImageView contained in the Android NavigationDrawer.

My Android app has a NavigationDrawer that contains an ImageView nested into a couple of other elements inside the NavigationDrawer header layout (app:headerLayout="@layout/navdrawer_header), and my navdrawer_header.xml has the following structure:

<LinearLayout android:id="@+id/navdrawer_header">
    ...
    <ImageView android:id=@+id/image_view
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    ...
</LinearLayout>

I am setting the image (img.jpg in my drawable folder) via

ImageView imageView = (ImageView) view.findViewById(R.id.image_view);
imageView.setImageResource(R.drawable.img);

If called from OnCreate inside my MainActivity, the imageView will be null and the app crashes. The same if I move the above lines to OnPostCreate or even OnStart. My understanding is that the view is not initialized yet at that point in time and therefore findViewById returns null. As a workaround, I have overwritten the OnDrawerOpened method and moved my code from above to that method. This works just fine, but I am pretty sure it is not the best way to go since the method is called every time the drawer is opened. Instead, I would need a method that is only called once upon the creation of the drawer.

What is the best practice here, i.e. where should I set the resource of an ImageView that is contained in the NavigationDrawer?

I have tried omitting view. and experimented with different values of view, for example by assigning to it the NavigationView or DrawerLayout associated with my drawer, but it does not solve the issue.

mattu
  • 944
  • 11
  • 24

1 Answers1

2

Try this:

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View view = navigationView.getHeaderView(0);

ImageView imageView = (ImageView) view.findViewById(R.id.image_view);
imageView.setImageResource(R.drawable.img);
Pang
  • 9,564
  • 146
  • 81
  • 122
Rohit Heera
  • 2,709
  • 2
  • 21
  • 31