Android: onBackPressed() not being called when navigation drawer open

前端 未结 8 1919
粉色の甜心
粉色の甜心 2021-02-05 05:54

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

8条回答
  •  旧巷少年郎
    2021-02-05 06:54

    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()":

    
    
    

    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();
    

提交回复
热议问题