1

My Problem:

I have a MainActivity along with its XML file activity_main.xml , which contains a NavigationDrawer view and that view calls a header.xml file to be displayed in my drawer.

The issue is that my header file contains a button so that when I click the header it opens a site. However since upgrading my Android studio build tools to 23.0.2 the onClick() for tht button inside my MainActivity crashes the app, giving me a NullPointerException.

I figure that its crashing because the header file is a totally different file from my activity_main.xml so my MainActivity would not have direct access to views inside of the header file.

How can I get access to the button that is inside the header.xml file with and also make it clickable?

Equivocal
  • 912
  • 2
  • 14
  • 27

2 Answers2

1

Solved:

The NullPointerException was due to the fact that the layout(Header.xml) containing my Button was not readily available for the MainActivity's xml layout, therefore findViewById would always be null because to it, the button doesn't exist. This question was solved by including the header.xml with all its contents(specifically the button) into the NavigationView of the MainActivity.xml

Like so:

<android.support.v4.widget.DrawerLayout ....>

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<include
    android:id="@+id/toolbar"
    layout="@layout/tool_bar" />

....

</RelativeLayout>


<android.support.design.widget.NavigationView
...

<include
    layout="@layout/header" />

</android.support.v4.widget.DrawerLayout>
Equivocal
  • 912
  • 2
  • 14
  • 27
  • i face this problem and can't solve it ,i'm not using navigation drawer i use recycleview with(header,items) how to make listener at – Amal Kronz Jan 03 '16 at 21:02
0

You can set the HeaderView of your NavigationView in your activity onCreate() method and set a listener to the header view like :

yourNavigationView.addHeaderView(yourHeaderView);
yourHeaderView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Handle the click event
        }
    });
Bubu
  • 1,533
  • 14
  • 14