How to disable or hide a Drawer Layout from Fragment Android

You could do something like this in your Fragment:

private MainActivity main;

@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        main = (MainActivity) activity;
    }

You definitely should avoid this!

A mutch better solution would be to use an Interface to communicate between your Main and the Fragment. You will end up with something like this:

public interface MyInterface {
 public void lockDrawer();
 public void unlockDrawer();
}

Main:

public class DetailViewActivity extends AppCompatActivity implements MyInterface {
 @Override
    public void lockDrawer() {         
      mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }

 @Override
    public void unlockDrawer() {
     mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
    }

}

Fragment:

   public class MyFragment extends Fragment {
     private MyInterface myInterface;

     @Override
     public void onAttach(Activity activity) {
      super.onAttach(activity);
       try {
        myInterface = (MyInterface) activity;
           } catch (ClassCastException e) {
              throw new ClassCastException(activity.toString() + " must implement MyInterface");
            }
        }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        myInterface.lockDrawer();
        return inflater.inflate(R.layout.example_fragment, container, false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        myInterface.unlockDrawer();
    }

}

Why this is the best solution: If you do something like ((HomeActivity) mActivity) you will not be able to reuse your Fragment. There will be a ClassCastException. In order to reuse your Fragment you should use an Interface instead of casting you MainActivity. So every Activity which will use your Frament can simply implement this Interface. Even if there's no DrawerLayout you can use it. So the big effort is reusability.


You can do this by following way -

Write one public method inside your activity as follows -

public void enableDisableDrawer(int mode) {
    if (mDrawerLayout != null) {
        mDrawerLayout.setDrawerLockMode(mode);
    }
}

and then inside fragment's onResume you can call this and change Drawer lock mode as required -

((HomeActivity) mActivity).enableDisableDrawer(DrawerLayout.LOCK_MODE_UNLOCKED);

OR

((HomeActivity) mActivity).enableDisableDrawer(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

where mActivity is my activity reference.

This way is working for me.

Tags:

Android