Search code examples
androidfragment

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

Solution

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