I have MainActivity which is holding 2 fragments. First fragment has navigation drawer, the second fragment not. In the MainActivity i want to override onBackPressed() method so when the navigation drawer is opened, it has to close the fragment. But i don't know how to get fragment's navigation drawer's state from Activity. Here's the code :
MainActivity.java
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
FragmentListProduct.java
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.fragment_list_product_layout, container, false);
Toolbar toolbar = (Toolbar) mainView.findViewById(R.id.toolbar);
fragmentActivity.setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) mainView.findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(fragmentActivity, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(drawerToggle);
drawerToggle.syncState();
navigationView = (NavigationView) mainView.findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_cat_all);
}
Of course it gives me error Cannot resolve symbol darwerlayout.
Before i made drawerLayout as a static field, but i got warning Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run). So how to solve this problem, or maybe you have another solution :D
You can access the fragment using the tag, which you'll have to assign when invoking the fragment, like this:
getFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment, "the_tag_here")
.commit();
Access it using getFragmentManager().findFragmentByTag("the_tag")
#Override
public void onBackPressed() {
FragmentListProduct fragment = (FragmentListProduct) getFragmentManager().findFragmentByTag("the_tag_here");
if (fragment != null) {
DrawerLayout drawerLayout = fragment.drawerLayout;
//make drawerLayout public in the fragment
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}
Solution 1:
Put your navigation drawer in your main activity.
open the second fragment in the new activity if you do not want navigation drawer there.
Solution 2:
Create a method in your fragment say checkNavigationDrawer().
Get a fragment reference in your activity like this
Fragment yourFragment = (YourFragment)getSupportFragmentManager().findFragmentById(R.id.containerId);
In your onBackPressed () call yourFragment.checkNavigationDrawer(); like this
#Override
public void onBackPressed() {
yourFragment.checkNavigationDrawer();
super.onBackPressed();
}
In your checkNavigationDrawer method check if the navigation drawer is open or not if it is open close it.
public void checkNavigationDrawer(){
if(drawerLayout.isOpen()){
drawerLayout.closeDrawers();
}
}
Hold your FragmentListProduct object in your MainActivity.
Create one method called isDrawerOpen() in the FragmentListProduct fragment.
Now you can call the isDrawerOpen() from MainActivity by using the FragmentListProduct class object.
Go for it!
Related
Introduction
I have an activity (let's call BaseActivity) that initializes the drawer layout in onPostCreate
public void initDrawerLayout(){
setSupportActionBar(getYellowToolbar());
getSupportActionBar().setDisplayShowTitleEnabled(false);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setScrimColor(getResources().getColor(R.color.blue_menu));
// Toggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
getYellowToolbar(), R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
EventBus.getDefault().post(new UiHelper());
}
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
findViewById(R.id.menu_back).setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view) {
mDrawerLayout.closeDrawer(Gravity.LEFT);
}
});
mExpandableListView = (ExpandableListView) findViewById(R.id.listmenu);
mExpandableListView.setOnGroupClickListener(this);
mExpandableMenuAdapter = getMenuAdapter();
mExpandableListView.setAdapter(mExpandableMenuAdapter);
mDrawerToggle.syncState();
}
Then I have a specific fragment working under an Activity which extends BaseActity.
This fragment adds to the top toolbar (yellowtoolbar) at onResume time an additional button inside R.menu.scanner_menu.
Toolbar toolbar = getYellowToolbar();
if (toolbar == null)
return;
toolbar.getMenu().clear();
toolbar.inflateMenu(R.menu.scanner_menu);
/**
* Add click listener on scan
*/
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
.
.
return false;
}
});
Situation
BaseActivity onPostCreate init drawer layout
ChildrenActivity extends BaseActivity
Fragment inflates new button onResume
Problem
When I reach this fragment from another fragment belonging to the same activity the inflate of the additional button is successful and I can click it with no problem.
While if I starts the application (so the onPostCreate of the BaseActivity is called) having the fragment to be shown at first so both the initDrawerLayout from BaseActivity and the inflate of the fragment are called almost at the same time the inflate of the additional button is unsuccessful and I cannot see it.
Additional info
I have tried to add a generic button in the fragment and clicking on it inflates one more time the menu button in the top toolbar and it correctly works. I think the problem seems to be the toolbar rendering by the drawer layout initialization that is still not completed the moment the fragment inflates the new button, so the toolbar just skip the new button and goes on with the BaseActivity.
I want to make on my MainActivity a property navigation for my users with hamburger and back arrow.
When I have only one fragment set hamburger, but if i have more fragments added on my MainActivity, set the back arrow.
How do I implement that?
Here is my implementation...
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Toolbar toolbar;
private DrawerLayout drawer;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setSupportActionBar(toolbar);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
//TODO: Insert back arrow button if have more than one fragment on backstack
/*getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
int stackHeight = getSupportFragmentManager().getBackStackEntryCount();
if (stackHeight > 0) {
if (getSupportActionBar() != null) {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.setDrawerIndicatorEnabled(false);
}
} else {
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.setDrawerIndicatorEnabled(true);
}
}
}
});*/
ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), new ListVeiculoFragment(), R.id.container_main);
}
}
Work by creating Interface class:
public interface HideShowIconInterface{
void showHamburgerIcon();
void showBackIcon();
}
Implement Interface in your Activity:
public class YourActivity extends AppCompatActivity implements HideShowIconInterface{
#Override
public void showHamburgerIcon() {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mActionBarDrawerToggle.setDrawerIndicatorEnabled(true);
}
#Override
public void showBackIcon() {
mActionBarDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
In your Fragment, call whatever you want by:
((HideShowIconInterface) getActivity()).showHamburgerIcon();
or
((HideShowIconInterface) getActivity()).showBackIcon();
You have to catch the moment when the numbers of the fragments change and use this code to hide (false) / show (true) the DrawerToggle "Hamburger"
mDrawerToggle.setDrawerIndicatorEnabled(false);
EDIT:
In your Activity (somewhere) you have something like this (where you change current Fragment):
private void selectItem(int position) {
Fragment fragment = new MyFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
}
I would change last line by this:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack(null)
.commit();
and then check:
if(fragmentManager.getBackStackEntryCount() > 1) mDrawerToggle.setDrawerIndicatorEnabled(false);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.app_name);
toolbar.setTitleTextColor(getResources().getColor(R.color.colorWhite));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
put this code in your activity where you use humbarger style navigation it work for me.
Actually none of above solutions works fully.
There are couple of issues that have to be considered -
a) if using ActionBarDrawerToggle then getSupportActionBar().setDisplayHomeAsUpEnabled is now working as expected - it actually replaces icon for toggle, but clicks are still handled by toggle plus hamburger icon is hidden when toggle is enabled again
b) As fragments transaction (add, restore form backstack) are done asynchronously, check for actual backstack size has to be done after fragment transaction is done - e.g. from fragments onCreateView
Here is code that works for me (in Kotlin):
override fun onCreate(savedInstanceState: Bundle?) {
// ....
drawerToggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(drawerToggle)
drawerToggle.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white)
drawerToggle.syncState()
drawerToggle.setToolbarNavigationClickListener {
// whatever action is needed on homeAsUp click
onBackPressed()
}
//And this method should be called from fragment's onCreateView
fun showUpNavigation() {
drawerToggle.isDrawerIndicatorEnabled=supportFragmentManager.getBackStackEntryCount() <= 1
}
You just add
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
For more details see Android - Switch ActionBar Back Button to Navigation Button.
I am trying to set up proper navigation in my application, which replaces Fragments in a main content area, so I have only one single Activity. I have one main Fragment and several subFragments, for example a Fragment for preferences. Everything works fine when using the back button, but I want to implement the up navigation including icon in addition to this. I am using the ActionBar fetched with Activity.getSupportActionBar() together with a Toolbar from appcompat and an ActionBarDrawerToggle.
I followed this tutorial when setting up my Drawer in the first place.
Current behavior:
When I start the app, the list/drawer icon is shown in the left part of the ActionBar. When I click this, the Drawer opens and I can select items. Sub Fragments are replaced into my content and the back button pops the stack, taking me back to the previous Fragment.
Missing behavior:
The list/drawer icon in the top left is never replaced by the back arrow icon and I cannot figure out how to implement this properly. The Drawer is always pulled out when clicking the list/drawer icon, no matter which Fragment I am in.
What have I tried:
I tried following this answer. It kinda works, meaning that the back arrow icon is set in the sub Fragments, but clicking the back arrow still opens the Drawer instead of providing up navigation. Also, when using the back button to go "up", the list/drawer icon is replaced by nothing.
I also tried following this answer. Here, the desired ActionBar behavior/look is implemented in the onCreate() method of the various Fragments. Using this I could get the back arrow up, but still the Drawer is pulled when clicking the arrow.
Various other minor things and hacks.
My questions:
What is wrong in my code below?
Is it correct/normal to use the combination ActionBar, Toolbar and ActionBarDrawerToggle to implement the Drawer navigation together with up navigation?
MyActivity.onCreate():
#Override
protected void onCreate(Bundle savedInstanceState)
{
// Other stuff
// Setup drawer.
mDrawerFragment = (DrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.mm_navigation_drawer);
mDrawerFragment.initialize(this, (DrawerLayout)findViewById(R.id.mm_drawer_layout), toolbar);
}
DrawerFragment class
public class DrawerFragment extends Fragment
{
private MyActivity mMyActivity;
private MyActionBarDrawerToggle mMyBarDrawerToggle;
private DrawerLayout mDrawerLayout;
private FragmentDrawerListener mFragmentDrawerListener;
private View mContainerView;
public void initialize(MyActivity myActivity, final DrawerLayout drawerLayout, final Toolbar toolbar)
{
mMyActivity = myActivity;
mFragmentDrawerListener = mMyActivity;
mContainerView = myActivity.findViewById(R.id.mm_navigation_drawer);
mMyActionBarDrawerToggle = new MyActionBarDrawerToggle(myActivity, drawerLayout, toolbar, R.string.mm_drawer_open, R.string.mm_drawer_close);
mDrawerLayout = drawerLayout;
mDrawerLayout.setDrawerListener(mMyActionBarDrawerToggle);
mDrawerLayout.post(new Runnable()
{
#Override
public void run()
{
mMyActionBarDrawerToggle.syncState();
}
});
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState)
{
// Not relevant, just create and return the View.
}
}
MyActivity.onDrawerItemSelected()
The implementation of the interface FragmentDrawerListener is done in the MyActivity class. It simply replaces the content area with other Fragments, using FragmentTransactions.
#Override
public void onDrawerItemSelected(View view, int postion)
{
switch (postion)
{
case DrawerAdapter.ITEM_FILTERED_RECIPES:
showFilteredRecipesFragment();
break;
case DrawerAdapter.ITEM_SELECTED_RECIPES:
showSelectedRecipesFragment();
break;
case DrawerAdapter.ITEM_SHOPPING_LIST:
showShoppingListFragment();
break;
case DrawerAdapter.ITEM_SETTINGS:
showSettingsFragment();
break;
case DrawerAdapter.ITEM_ABOUT:
showAboutFragment();
break;
}
}
MyActionBarDrawerToggle class
public class MyActionBarDrawerToggle extends ActionBarDrawerToggle
{
private MyActivity mMyActivity;
private Toolbar mToolbar;
public MyActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes)
{
super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes);
mMyActivity = (MyActivity) activity;
mToolbar = toolbar;
}
#Override
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
mMyActivity.invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView)
{
super.onDrawerClosed(drawerView);
mMyActivity.invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
mToolbar.setAlpha(1 - slideOffset / 2);
}
}
The DrawerFragment is inflated in the main layout using a simple, static Fragment instance like this:
<fragment
android:id="#+id/my_navigation_drawer"
android:name="com.my.company.gui.drawer.DrawerFragment"
android:layout_width="#dimen/my_nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/my_drawer_navigation_fragment"
tools:layout="#layout/my_drawer_navigation_fragment">
</fragment>
If you're using material design for you app, then it is expected that you use the Toolbar to replace the Actionbar in your activity. You will still maintain your ActionBarDrawerToggle and functionality will remain the same.
As for your fragments, as long as they are 'housed' by the same activtiy (i.e the activity with the drawer), changing fragments will not cause the drawer toggle to change the back arrow. It will only change if you navigate to a new activity. Only then will the main activity be treated as home and with the other activities having a back arrow to navigate back
I'm scratching my head with this one now.... I have an ActionBarActivity that loads an initial Fragment - the original menu is inflated within the activity. Now, I have a navigation bar that, when an item is selected, loads a different fragment and adds this to the backstack.
When I do this, there are a couple of things I want to set:
Set the home as up indicator
Invalidate the options menu from the main activity
Set has options to true for the Fragment
Ensure that the up indicator correctly navigates back to the original Fragment
Something rather strange is going on - the up indicator appears once only and does not behave as the back button and although I've invalidated and inflated a new menu, the new menu gets appended to the original Activity menu.
EDIT: Ok I've resolved the appending issue - forgot to add menu.clear() in the onCreateOptionsMenu method.
My navigation drawer layout has onClick methods to all menu items which would trigger the load of another Fragment:
public void navItemClick(View view) {
switch (view.getId()) {
case R.id.ripSMS:
mNavigationDrawer.toggleHome(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
FragmentTransaction mTrans = getSupportFragmentManager().beginTransaction();
mTrans.replace(R.id.voiceover_frame_layout,new MessageFragment(),"main_ui")
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).addToBackStack("msg").commit();
break;
case R.id.ripEmail:
break;
case R.id.ripSettings:
break;
}
mNavigationDrawer.closeDrawer();
}
toggleHome:
public void toggleHome(boolean show) {
mDrawerToggle.setDrawerIndicatorEnabled(show);
if (!show) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
} else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
}
Once the item is triggered the onCreate contains the invalidate and the hasOptions code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().invalidateOptionsMenu();
setHasOptionsMenu(true);
}
The onCreateOptionsMenu then inflates another menu layout (contains a single item called settings).
As mentioned, this only partially works once - the first time I use the item to load the Fragment, I get the back icon but it's also not working (this is set within onOptionsItemSelected to check for the home item press - it does nothing). When I press the back button it takes me back to the correct place. If I navigate back however, the back arrow now longer shows even though the code runs through onCreate!
Ok so I managed to solve this after some trial and error. Two changes made:
Implement addOnBackStackChangedListener
ActionBarDrawerToggle's setToolbarNavigationClickListener needed to be set
As I only have one activity (everything else is Fragment classes) I added the backstack listener to the Parent Activity's onCreate method:
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
}
});
This resolved the disappearing back arrow when going back to the fragment. Finally added the listener to my NavigationDrawer's setup class:
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
I suppose the only questions I have is everything pointed towards using the onOptionsItemSelected method with android.R.id.home but this never worked for me. It might be the way I've implemented things of course but if someone sees anything obvious as to why please do let me know!
These steps helps you to show back button in toolbar when a fragment is loaded. And to pop out when its clicked.
Set setNavigationOnClickListener to toolbar in you activity.
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getSupportFragmentManager().getBackStackEntryCount() > 0){
getSupportFragmentManager().popBackStack();
}else {
drawer.openDrawer(GravityCompat.START);
}
}
});
Implement FragmentManager.OnBackStackChangedListener in you Activity. And register it with SupportFragmentManager in OnCreate()
getSupportFragmentManager().addOnBackStackChangedListener(this);
OnBackStackChangedListener Implementation method:
#Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() > 0){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.syncState();
}
}
For me the above answer was not enough, but i've used #Hamz4h_ and added some more after digging into the ActionBarDrawerToggle class. I'm just calling this method of mine from the activity's onCreate:
private void initNavigationElements() {
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mBinding.drawerLayout, mBinding.appBarMain.toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mBinding.drawerLayout.addDrawerListener(toggle);
// Tricking the toggle by giving it its own arrow as a custom indicator.
// It will use it when setDrawerIndicatorEnabled is called with false
toggle.setHomeAsUpIndicator(toggle.getDrawerArrowDrawable());
toggle.syncState();
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
DrawerArrowDrawable drawerArrowDrawable = toggle.getDrawerArrowDrawable();
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
// 1 - Display as arrow
drawerArrowDrawable.setProgress(1);
toggle.setDrawerIndicatorEnabled(false);
} else {
// 2 - Display as arrow menu
drawerArrowDrawable.setProgress(0);
toggle.setDrawerIndicatorEnabled(true);
}
}
});
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// This is called only when setDrawerIndicatorEnabled is set as false, meaning we are not at the "root" fragment.
getSupportFragmentManager().popBackStackImmediate();
}
});
}
Hope this will help someone :)
I have made an app with one activity which uses a navigation drawer to open a number of different fragments. I have the actionbar drawertoggle, but it is not very visible.
If I place a button in the onCreateView in my main fragment(the fragment that appears when my app first starts up), how can I get it to open the navigation drawer controlled by my activity?
This seems to work. The answer is much simpler than I thought it would be.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragView = inflater.inflate(R.layout.mainmenu, container, false);
button1 = (Button) fragView.findViewById(R.id.button1);
mDrawerLayout = (DrawerLayout)getActivity().findViewById(R.id.drawer_layout);
mDrawerList = (ListView)getActivity().findViewById(R.id.left_drawer);
button1.setOnClickListener(this);
return fragView;
}
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(mDrawerList);
}
Thank you for your answers.
if you need open the slide:
mDrawerLayout.openDrawer(Gravity.LEFT); //Edit Gravity.START need API 14
if you need close the slide
mDrawerLayout.closeDrawer(Gravity.LEFT); //Edit Gravity.START need API 14
EXAMPLE
my mDrawerLayout is instanced here:
mDrawerLayout = (DrawerLayout)findViewById(R.id.my_drawer_layout);
my slide state:
mSlideState=false;
if you need to know the slide menu state (closed, opened). Use this code:
mDrawerLayout.setDrawerListener(new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.ic_menu_slide,
0,
0){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
mSlideState=false;//is Closed
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
mSlideState=true;//is Opened
}});
finally. You can use your click event like this:
public void clickEventSlide(){
if(mSlideState){
mDrawerLayout.closeDrawer(Gravity.END);
}else{
mDrawerLayout.openDrawer(Gravity.END);
}}
In my case, my slide menu is at the right (Gravity.END), but if you need it on the left, try with Gravity.START
You Should Use isDrawerOpen()
The piece of code below automatically closes or opens the navigation drawer based on the drawer's current state (Opened or 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 the navigation drawer is not open then open it, if its already open then close it.
if(!navDrawer.isDrawerOpen(Gravity.START)) navDrawer.openDrawer(Gravity.START);
else navDrawer.closeDrawer(Gravity.END);
}
});
if you are using from default navigation activity in android you just have to
add this code in click listener of button --->
mDrawerLayout.openDrawer(Gravity.START);
for closing you do not have to do something.
Use these lines to open and close the drawer on a certain event:
Code snippet for opening drawer:
drawerLayout.openDrawer(Gravity.START);
Code snippet for closing drawer:
drawerLayout.closeDrawer(Gravity.LEFT);
→ openDrawer(gravity_of_navigation_view_to_be_shown)
in openDrawer("gravity"), in "gravity" section, you have to input the gravity of the Navigation View like given above:
Gravity.LEFT
Gravity.RIGHT
Gravity.START
Gravity.END
I think thats the best answer.
To apply the toolbar as the app bar, first make sure your activity extends from AppCompatActivity. Then call setSupportActionBar() and pass the Toolbar object from your layout:
toolbar=(Toolbar) findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
drawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
ActionBarDrawerToggle actionBarDrawerToggle=new ActionBarDrawerToggle(this,drawerLayout,R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
}
The simplest way in my opinion
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(findViewById(R.id.navigationViewId))){
mDrawerLayout.closeDrawer(Gravity.LEFT);
}else
super.onBackPressed();
}