Handling back press when using fragments in Android

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

            view.setFocusableInTouchMode(true);
            view.requestFocus();
            view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event)   {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
    
    
                Fragment NameofFragment = new NameofFragment;
    
                FragmentTransaction  transaction=getFragmentManager().beginTransaction();
                transaction.replace(R.id.frame_container,NameofFragment);
    
                transaction.commit();
    
                return true;
            }
            return false;
        }
    });
    
    return view;
    

提交回复
热议问题