Android compare two fragments

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(); } } 
1

3 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(); } } 
2

Working 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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like