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 kn
I have a simpler solution which uses isDrawerOpen() of DrawerLayout
.
The code below closes or opens the navigation drawer based on the drawer's current state (Opened/Closed)
Button hamMenu = findViewById(R.id.ham_menu);
hamMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DrawerLayout navDrawer = findViewById(R.id.drawer_layout);
// If navigation drawer is not open yet, open it else close it.
if(!navDrawer.isDrawerOpen(GravityCompat.START)) navDrawer.openDrawer(Gravity.START);
else navDrawer.closeDrawer(Gravity.END);
}
});
Kotlin Solution
If you want to open it from a fragment, you can use:
activity?.drawerLayout?.openDrawer(GravityCompat.START)
or inside the activity directly:
drawerLayout.openDrawer(GravityCompat.START)
Note:
If you are not familiar with the '?', I highly recommend reading about null saftey from kotlin's documentation (It is very short don't worry): https://kotlinlang.org/docs/reference/null-safety.html
I wrote an answer about this here: https://stackoverflow.com/a/18199771/880349
//For me a better way in avoiding a `null pointer` in getting the DrawerLayout
final DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Opens the Drawer
drawer.openDrawer(Your View, Usually a ListView);
}
return false;
});
You directly get the current drawer inside a view/fragement so that you won't get a NullPointerException
Thanks to @athor & @Ashish Tana.
It took me so much time to figure out the error (NullPointerException
) I am getting.
Mine works this way; Instead of getView()
, I use getActivity()
and open the drawer by mDrawerLayout.openDrawer(Gravity.LEFT);
.
mDrawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
final ImageButton btnOpenDrawer = (ImageButton) getView().findViewById(R.id.drawer_menu);
btnOpenDrawer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(Gravity.LEFT);
}
});
It works on Button click
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
drawer.openDrawer(GravityCompat.START);
}
});
drawerLayout.openDrawer(Gravity.START);