I have 10 different fragments in my application. I need to hide Navigation drawer (Drawer Layout) in few fragments, how can I access Drawer Layout from a fragment and hide it? I know we need to use in activity mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
but how to do it in fragments?
To add a navigation drawer, first declare a DrawerLayout as the root view. Inside the DrawerLayout , add a layout for the main UI content and another view that contains the contents of the navigation drawer.
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.
com.google.android.material.navigation.NavigationView. Represents a standard navigation menu for application. The menu contents can be populated by a menu resource file. NavigationView is typically placed inside a DrawerLayout .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With