Reputation: 7131
I am creating an application with navigation drawer when I click each navigation list new fragments will load. One of the fragment have listView. When I click this list load another fragment. Now I move to different fragments using navigation drawer. When I press back button every time I want to move to previous fragment without any data change.How can I do it?
I am loading fragment using the following code:
FragmentManager fm = getFragmentManager();
for (int i = 0; i < fm.getBackStackEntryCount(); i++) {
fm.popBackStack();
}
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragmentHome, fr);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.commit();
In short:: Every back press I want to load previous fragment without recreating it
Upvotes: 1
Views: 2728
Reputation: 3275
I think this may help
Just Do PopBackStack
from Fragmentmanager
FragmentManager fm = getFragmentManager();
for (int i = 0; i < fm.getBackStackEntryCount(); i++) {
fm.popBackStack();
}
And In that Fragment
View mView ; //this will be global
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
try {
if (mView == null) {
// view will be initialize for the first time .. you can out condition for that if data is not null then do not initialize view again.
mView = inflater.inflate(R.layout.xml,container, false);
}
} catch (Exception e) {
e.printStackTrace();
}
return mView;
}
Upvotes: 5
Reputation: 1271
public void addFragment( final Fragment newFragment, final Fragment hideFragment) {
final FragmentManager fragmentManager = getFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.hide(hideFragment);
fragmentTransaction.add(R.id.container, newFragment, newFragment.getClass().getSimpleName());
fragmentTransaction.addToBackStack(hideFragment.getClass().getSimpleName());
fragmentTransaction.commitAllowingStateLoss();
}
Use this instead of replacing fragment.will solve your problem.
Upvotes: 0