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 Fragment appears. I move from one fragment to another fragment using the following code:
Fragment fragment =null;
fragment =newGalleryFragment(selectetdMainMenu.getCategoryID());FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.addToBackStack("menuFrag");
ft.add(R.id.frame_container, fragment,"menuFrag");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
In this way I can go from one fragment to another but I fail to come to the previous fragment on back button press. I managed to come up with this code to handle back press in MainActivity where Drawer is Initialized:
@Overridepublicboolean onKeyDown(int keyCode,KeyEventevent){super.onKeyDown(keyCode,event);if(keyCode ==KeyEvent.KEYCODE_BACK){Fragment fragment_byTag = fragmentManager.findFragmentByTag("menuFrag");Fragment menuFragment_by_tag = fragmentManager.findFragmentByTag("galleryFrag");Fragment commentsFrag_by_tag = fragmentManager.findFragmentByTag("commentsFrag");Fragment dealDetail = fragmentManager.findFragmentByTag("promoFrag");if(commentsFrag_by_tag !=null){if(commentsFrag_by_tag.isVisible()){Log.e("comments back "," clicked");//menuDetailsFrag.onBackPressed();FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().remove(commentsFrag_by_tag).commit();
fragmentManager.beginTransaction().show(menuFragment_by_tag).commit();}}elseif(menuFragment_by_tag.isVisible()){Log.e("menu back "," clicked");
menuDetailsFrag.onBackPressed();FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().remove(menuFragment_by_tag).commit();
fragmentManager.beginTransaction().show(fragment_byTag).commit();}}returnfalse;}
This works at times but fails most of the time. I would greatly appreciate if a better way to navigate back can be shown.
ft.addToBackStack(null);ft.commit();
add the fragments to the backstack and pop them. stackoverflow.com/questions/22550420/… – Raghunandan Mar 21 ‘14 at 7:45