I need help about an issue, in my android app that I am working on, I am navigating between Fragment
s all the time. I use the code to navigate between Fragment
s.
newsFeedFragment fragment = new newsFeedFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
With the code above, navigating to the news feed fragment loads from "onCreate
". HI need that if the fragment was loaded before, it should show the previously loaded page, the onCreate
should be skipped but the onResume
not. However, if the Fragment
was not loaded before the Fragment
should be loaded for the first time.
Could anyone help me about making this happen?
Thank you very much
You can do this by adding TAG to your fragments. Where ever you add a fragment to your view do this like the following:
getSupportFragmentManager().beginTransaction().replace(R.id.something, new SomeFragment(),"SOMETAG").commit();
and where ever you want to check whether this fragment is already exists to prevent reloading it add the following check:
SomeFragment sf = (SomeFragment) getSupportFragmentManager().findFragmentByTag("SOMETAG");
if(sf != null)
{
//the condition when the fragment is already exists
}
else
{
//the condition when the fragment is not loaded
}