When I change a fragment I would like to compare the new one with the current one. If they are the same, it is not necessary to replace them.
I tried
public void displayFragment(Fragment fragment){ FragmentManager fm = getSupportFragmentManager(); Fragment currentFragment = fm.findFragmentById(R.id.content_frame); if(!currentFragment.equals(fragment)) getSupportFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.content_frame, fragment).commit(); } but it does not work and the fragment is changed even if the new one is the same
A solution ? Thanks
EDIT
The solution :
public void displayFragment(Fragment fragment){ FragmentManager fm = getSupportFragmentManager(); Fragment currentFragment = fm.findFragmentById(R.id.content_frame); if(!fragment.getClass().toString().equals(currentFragment.getTag())){ getSupportFragmentManager() .beginTransaction() .addToBackStack(null) .replace(R.id.content_frame, fragment, fragment.getClass().toString()) // add and tag the new fragment .commit(); } } 13 Answers
One way to identify Fragments is to give them tags :
public void displayFragment(Fragment fragment, String tag){ FragmentManager fm = getSupportFragmentManager(); Fragment currentFragment = fm.findFragmentById(R.id.content_frame); if(!tag.equals(currentFragment.getTag()) getSupportFragmentManager() .beginTransaction() .addToBackStack(null) .replace(R.id.content_frame, fragment, tag) // add and tag the new fragment .commit(); } edit : alternative version from psv's comment, using classnames as tag :
public void displayFragment(Fragment fragment){ FragmentManager fm = getSupportFragmentManager(); Fragment currentFragment = fm.findFragmentById(R.id.content_frame); if(!fragment.getClass().toString().equals(currentFragment.getTag())) { getSupportFragmentManager() .beginTransaction() .addToBackStack(null) .replace(R.id.content_frame, fragment, fragment.getClass().toString()) // add and tag the new fragment .commit(); } } 2Working Simple code in Kotlin. Here Fragment_Current() is a current fragment.
fun displayFragment(fm: Fragment) { if(fm !is Fragment_Current){ supportFragmentManager.beginTransaction().replace(R.id.ContentFragmentRoot, fm).commit() } } Based on @alex-fu comment, the code should be something like this:
public void displayFragment(Fragment fragment){ FragmentManager fm = getSupportFragmentManager(); Fragment currentFragment = fm.findFragmentById(R.id.content_frame); if( !(fragment instanceof currentFragment) ) { getSupportFragmentManager() .beginTransaction() .addToBackStack(null) .replace(R.id.content_frame, fragment, fragment.getClass().toString()) // add and tag the new fragment .commit(); } } 2