There is a program that uses DrawerLayout, in which fragments are loaded from the menu (depending on where the user clicks).

The fragment download code itself is as follows:

public void loadFragment(Fragment fragmentTarget, String title) { if (fragmentTarget == null){ return; } Log.d(TAG, "load fragment " + title); FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.content_frame); if (fragment == null){ fm.beginTransaction().add(R.id.content_frame, fragmentTarget).commit(); } else { fm.beginTransaction().replace(R.id.content_frame, fragmentTarget) .addToBackStack(null).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).commit(); } title = getString(R.string.app_name) + " " + title; getSupportActionBar().setTitle(title); 

Actually the question: How to avoid the situation that the user clicking the same menu item twice in a row does not reload the fragment (the reload itself is not so terrible, but the fact that this fragment is added to the stack is not very good in terms of usability)

update I can of course keep the name of the current fragment loaded in the main activity in a variable, but it seems to me that it is not quite right

  • And why are you doing fm.beginTransaction().add . Always fm.beginTransaction().replace . This is essentially the design of the DrawerLayout pattern - pavel163
  • @ pavel163 because if I immediately replace, then at the initial boot I create an "empty fragment" of which I sort of replace for the initial boot I am replaced by the fragment that should be the first at my boot. Accordingly, to avoid displaying an “empty fragment” when I press the back button, I use this mechanism - plesser

1 answer 1

If you are so afraid of reloading fragments, you can hide them and show them when you need, using the FragmentManager and the name of the fragment (or another determinant).

 public void hideFragment(FragmentManager fragmentManager,String tag){ fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag(tag)).commit(); } public void showFragment(FragmentManager fragmentManager,String tag){ fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag(tag)).commit(); } public boolean isFound(FragmentManager fragmentManager,String tag){ if (fragmentManager != null) { List<Fragment> fragments = fragmentManager.getFragments(); if (fragments != null) { for (int i = fragments.size() - 1; i >= 0; i--) { Fragment fragment = fragments.get(i); if (fragment.getTag().equals(tag)) return true; } } } return false; } 
  • I’m not afraid of overloading, I don’t like the fact that I may have several identical fragments in the stack and as a result the user will get confused when he presses the back button - plesser