Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open Navigation Drawer with no actionbar, open with just a button

I have a navigation bar without any actionbar (I don't want an actionbar). I'm trying to make it so that I have a button that can open the navigation drawer.

I know there's a method called openDrawer for the DrawerLayout http://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html#openDrawer(android.view.View)

I didn't know how to use it, but i have tried making a button when click, runs this method:

DrawerLayout mDrawerLayout = (DrawerLayout) getView().findViewById(R.id.drawer_layout); mDrawerLayout.openDrawer(mDrawerLayout); 

When i click it on it, it gives me a Java NullPointerException. Anybody has any idea?

EDIT: This code is inside a fragment, and I'm trying to refer those drawer layout outside the fragment. I used debugger, and it is showing that mDrawlerLayout is NULL.

Any advice?

Thanks!

like image 214
CynthiaDDurazo Avatar asked Jul 23 '13 21:07

CynthiaDDurazo


People also ask

How do I open a navigation drawer?

The user can view the navigation drawer when they swipe a finger from the left edge of the activity. They can also find it from the home activity (the top level of the app) by tapping the app icon (also known as the Android "hamburger" menu) in the action bar.

What is DrawerLayout?

DrawerLayout acts as a top-level container for window content that allows for interactive "drawer" views to be pulled out from one or both vertical edges of the window.


2 Answers

It's giving you a null pointer because you are trying to find the drawer layout in the fragment's view, when it is actually in the activities view.

A quick hack to do what you want is to find the view like:

getActivity().findViewById(R.id.drawer_layout) 

That should work. A better way is to have a method on the activity for opening the drawer

public void openDrawer(){     mDrawerLayout.openDrawer(mDrawerLayout); } 

In the activity onCreate run your findViewById:

mDrawerLayout = (DrawerLayout) getView().findViewById(R.id.drawer_layout); 

mDrawerLayout should be a member variable of your activity.

Then in your fragment you can call:

//cast activity to MyActivity so compiler doesn't complain ((MyActivity)getActivity()).openDrawer(); 

An even better way to do it is to create a listener in the fragment and set the activity as a listener to the fragment. Then you can call a method on the activity, similar to above. I'll let you do some research on how to do that.

like image 149
athor Avatar answered Oct 10 '22 12:10

athor


drawerLayout.openDrawer(Gravity.START); 
like image 23
Aliya Avatar answered Oct 10 '22 10:10

Aliya