Android compares two fragments

When I change a fragment, I would like to compare the new with the current. If they are the same, they do not need to be replaced.

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 doesn’t work, and the fragment changes even if the new one is the same

Decision? Thanks

EDIT

Decision:

 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(); } } 
+4
source share
2 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: alternate version from psv comment using cool names 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(); } } 
+6
source

Based on the @ alex-fu comment, the code should look 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(); } } 
0
source

Source: https://habr.com/ru/post/1498634/


All Articles