Handling back press when using fragments in Android

前端 未结 5 904
一整个雨季
一整个雨季 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:43

    In your oncreateView() method you need to write this code and in KEYCODE_BACk condition you can write whatever the functionality you want

       View v = inflater.inflate(R.layout.xyz, container, false);
        //Back pressed Logic for fragment
        v.setFocusableInTouchMode(true);
        v.requestFocus();
        v.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        getActivity().finish();
                        Intent intent = new Intent(getActivity(), MainActivity.class);
                        startActivity(intent);
    
                        return true;
                    }
                }
                return false;
            }
        });
    

提交回复
热议问题