avoid reloading on back pressed in fragments

userAndroid picture userAndroid · Mar 31, 2014 · Viewed 12.4k times · Source

I am making an app for car finding.I am showing result in gridview and also have a sliding menu on right hand side(for search filter).I have made this whole app with the help of fragments.In the gridview I have a load more footer at bottom, when I click on 12th position gridview , I am starting another fragments like this:

SearchDetailActivity.goToFragment(ProductDetailFragment.newInstance(map,position));

and in ProductDetailFragment I have a back button,to go back on previous fragment like this:

SearchDetailActivity.goToFragment(SearchDetailFragment.newInstance(str_url));

Now when I came back again data shows from 0-10th item.

In goToFragment() I have write this code:

public static void goToFragment(Fragment fragment) {
    Log.d("GoToFrag","sjdk>>"+fragment);
    Fragment tmp = fm.findFragmentByTag(fragment.getClass().getName());
    if (tmp != null && tmp.isVisible())
        return;

    ft = fm.beginTransaction();
    ft.replace(R.id.main_fragment, fragment, fragment.getClass().getName());
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    ft.commit();
    currentTag = fragment.getClass().getName();
}

I want to avoid data reload when come back from ProductDetailFragment.If I used Activity then I can use onBackPressed() to back and avoid reloading but in Fragment when I pressed app's back button ,It reload the SearchDetatilFragment,which is very annoying..Please help me..Thanks in advance.

Answer

Durga Mohan picture Durga Mohan · Feb 9, 2015

I have stumbled on this issue for about 3 months. Finally my efforts were paid off and found a solution.

The problem is, when you user "replace", this is equivalent to "remove and add". so the fragment is completely removed and recreated when back button is pressed. instead we have to hide the parent fragment and show the child.

Where serach fragment is called

 ft = fm.beginTransaction();
 ft.replace(R.id.main_fragment, yourSearchFragment, "searchFragment");
 ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
 ft.commit();

When calling productDetails fragment

 ft = fm.beginTransaction();
 ft.hide(getFragmentManager().findFragmentByTag("searchFragment"));
 ft.add(R.id.main_fragment, yourDetailfragment);
 ft.addToBackStack(null);
 ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
 ft.commit();

Good luck