I have a main activity that is situated with two navigation drawers. The left one is always accessible, but the right one is used for displaying some necessary lists and perform
I had a very similar issue with an empty list in a fragment (wouldn't respond to back button press when the list was empty) and some of the solutions mentioned here helped me solving my issue.
The fragment causing the issue with the "onBackPressed()":
<TextView
android:id="@android:id/empty"
... />
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
The issue is similar in that when the list returned by the adapter is empty (@android:id/empty), the first view (TextView) doesn't seem to be "considered" as a focusable/focused view by Android (whereas the second view - ListView - is).
So pressing the back button wouldn't be registered by the view currently displayed and wouldn't be caught by my custom code in the fragment (instead closing the activity directly).
In my case, adding the following to onCreateView solved my issue (and allowed the back button press to be caught by the fragment even when the list is empty):
View view = inflater.inflate(R.layout.fragment_content, container, false);
view.setFocusableInTouchMode(true);
view.requestFocus();
The problem, as @Alex Vasilkov indicated, seems to do something with the drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
method.
None of the suggestions above did work for me. So I wanted to write my own solution. I digged the source code of DrawerLayout Class and tried overriding onKeyDown
and onKeyUp
methods, but the Back Button click is not getting triggered at all, if the Lock mode is LOCK_MODE_LOCKED_CLOSED
. I think this is a bug.
So in my case, I needed to lock left navigation drawer only, not the right one. And I ended up calling drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.START);
this method to lock my left navigation drawer instead of calling drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
this method, which locks both of the drawers and causes this back button bug.
So as a summary, drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
disables back button click somehow. Maybe only if you have two navigation drawers.