Dan Ponce Dan Ponce - 2 months ago 28
Android Question

Navigation View header click listener not working

For some reason the header of my Navigation View is not working for me. I have followed the other posts answers but I still have the same problem. This is my code:

navigationView = (NavigationView) findViewById(R.id.nav_view);

View header = navigationView.getHeaderView(0);

linearLayoutUserProfile = (LinearLayout) header.findViewById(R.id.linearUserProfile);

linearLayoutUserProfile.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(MenuActivity.this,"Click header", Toast.LENGTH_SHORT).show();
//Intent mIntent = new Intent(MenuActivity.this, ProfileActivity.class);
//startActivity(mIntent);
}
});


Anyone can give me any tips?

FIND A
SOLUTION, READ BELOW

Answer

After searching and searching I figured out that you don't have to add more xml code after your navigation view:

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_menu"
    app:menu="@menu/activity_menu_drawer"/>

It's best to leave this navigation view tab at the end of your "activity_main.xml" (Or whatever your xml where your Navigation View is) This is my "nav_header_menu.xml":

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="@dimen/nav_header_height"
          android:id="@+id/linearUserProfile"
          android:background="@drawable/background_wheat"
          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:clickable="true"
          android:theme="@style/ThemeOverlay.AppCompat.Dark">

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

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textViewNombre"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:text="Some name"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>

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

</LinearLayout>