java – How to prevent reloading the visible fragment on Android?

Question:

I am creating a side menu using fragment loading, I need to prevent the loading of the fragment if it is currently showing, that is to avoid a duplicate loading

I currently have this code for fragment loading

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
...    
Fragment newFragment = null;
..
newFragment = FragmentHome.newInstance(title,id);
...
newFragment = FragmentSenderos.newInstance(title);

//carga de fragmento
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
        .replace(R.id.frame_layout, newFragment,nameNewFragment)
        .addToBackStack("F_MAIN")
        .commit();

Answer:

Solved! , the next method independent of the fragments loaded or available to load. Just check if the new fragment to load is the same one that is being displayed, regardless of whether it is already loaded or not previously.

LoadFragment function to load a fragment

private void loadFragment(Fragment newFragment) {
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.frame_layout, newFragment,newFragment.getClass().getName())
            .addToBackStack("F_MAIN")
            .commit();
}

code to prevent duplicate loading of the visible fragment

if (newFragment != null) {

    Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.frame_layout);

    if (currentFragment == null) {
        //carga del primer fragment justo en la carga inicial de la app     
        loadFragment(newFragment);
    } else if (!currentFragment.getClass().getName().equalsIgnoreCase(newFragment.getClass().getName())) {
        //currentFragment no concide con newFragment
        loadFragment(newFragment);

    } else {
        //currentFragment es igual a newFragment
    }
}

In the variable currentFragment load the current fragment of the frame layout. If currentFragment is Null, it means that it is when the app is launched for the first time, the initial fragment is loaded. If there is a fragment in the fragment container, it is compared with the new fragment to load newFragment .

Scroll to Top