Android MaterialDrawer返回键问题:按返回键退Activity而非关闭抽屉
Hey there! This isn't a bug—it's just Android's default behavior kicking in. By default, the back button will finish the current Activity when pressed, regardless of whether a drawer is open. But don't worry, there's an easy fix to make it close the drawer first before navigating back.
Here's how to handle it:
1. Get your Drawer instance
First, make sure you have a reference to your MaterialDrawer instance that you created with DrawerBuilder. For example:
Drawer drawer = new DrawerBuilder() .withActivity(this) // Add your other drawer configurations here .build();
2. Override the back button logic
You need to intercept the back press event and check if the drawer is open. If it is, close the drawer instead of finishing the Activity.
Option 1: Traditional onBackPressed() override (Java)
@Override public void onBackPressed() { if (drawer.isDrawerOpen()) { drawer.closeDrawer(); } else { // Let Android handle the back press normally if drawer is closed super.onBackPressed(); } }
Option 1 (Kotlin):
override fun onBackPressed() { if (drawer.isDrawerOpen) { drawer.closeDrawer() } else { super.onBackPressed() } }
Option 2: Modern OnBackPressedCallback (recommended for newer Android versions)
If you're using AndroidX, this is the more flexible approach:
Java:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // ... your other setup code drawer = new DrawerBuilder().withActivity(this).build(); getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) { @Override public void handleOnBackPressed() { if (drawer.isDrawerOpen()) { drawer.closeDrawer(); } else { // Remove this callback and trigger default back behavior remove(); getOnBackPressedDispatcher().onBackPressed(); } } }); }
Kotlin:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... your other setup code drawer = DrawerBuilder().withActivity(this).build() onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { if (drawer.isDrawerOpen) { drawer.closeDrawer() } else { remove() onBackPressedDispatcher.onBackPressed() } } }) }
Why this works
MaterialDrawer doesn't automatically handle back presses because Android's default behavior prioritizes finishing the current Activity. By adding this check, you're telling the app to first handle the drawer state before falling back to the default back action.
内容的提问来源于stack exchange,提问作者TheAndoOne

