Handling back press when using fragments in Android

前端 未结 5 970
一整个雨季
一整个雨季 2021-01-30 12:00

I am using Android Sliding Menu using Navigation Drawer in my application and Fragments are used in the app instead of Activities. When I open the drawer, click on an item a Fra

5条回答
  •  清歌不尽
    2021-01-30 12:24

    I usually set an onKeyListener to the View in onResume. From what I learned you have to take care to set setFocusableInTouchMode() and requestFocus on the View.

    This is a sample of what I use for this purpose:

    @Override
    public void onResume() {
    
        super.onResume();
    
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
    
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
    
                    // handle back button
    
                    return true;
    
                }
    
                return false;
            }
        });
    }
    

提交回复
热议问题