Avoid reloading on back pressed in fragments

I am making a car search application. I show the result in gridview, and also have a sliding menu on the right side (for the search filter). I made this application using fragments. In gridview, I have a load greater than the footer below, when I click on gridview 12th position, I start doing the following snippets as follows:

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

and in ProductDetailFragment I have a return button to go back to the previous snippet, like this:

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

Now that I'm back, the data is showing from point 0.

In goToFragment () I wrote 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 reloading when I return from ProductDetailFragment. If I used Activity, then I can use onBackPressed () to return and avoid reloading, but in Fragment, when I pressed the back button, it reloads SearchDetatilFragment, which is very annoying .. Please help me .. Thanks in advance.

+6
source share
2 answers

I came across this problem for about 3 months. Finally, my efforts were extinguished and found a solution.

The problem is that when the user "replaces", it is equivalent to "remove and add". therefore, the fragment is completely deleted and recreated when you click the "Back" button. instead, we should hide the parent fragment and show it.

In the case where the 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 a productDetails snippet

  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.

+19
source

Use getFragmentManager (). popBackStack () on the back of the fragment, this will load the previous fragment and not create a new one.

For the back back button, configure the listener as follows:

 View.OnClickListener mBackListener = new View.OnClickListener() { @Override public void onClick(View v) { getFragmentManager().popBackStack(); } }; 
-1
source

All Articles