java – How to prevent reload visible fragment in Android?

Question:

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

I currently have this code for snippet upload

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 following method independent of the fragments loaded or available to load. It only checks if the new fragment to load is the same as the one being displayed, regardless of whether it is already loaded or not.

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 currentFragment variable I load the current fragment of the frame layout. If currentFragment is Null, it means that when the app is first launched, the initial fragment is loaded. If there is a fragment in the fragment container it is compared to the new fragment to load newFragment .

Scroll to Top