Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List view reload when back pressed in fragment

I have Fragment XYZFragment where i display the list view.On the Listview item click i replace the Fragment like this.

Fragment fragment=new XYZFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft= fragmentManager.beginTransaction();
ft.addToBackStack(null);
ft.replace(R.id.content_frame, fragment).commit();

But my problem is when i click back button the fragment reload the listview.It is never happen when i used to use Activity. So my question is how to save the instance of previous fragment so that it will prevent the reloading of Data.

like image 688
Mr Nice Avatar asked Dec 29 '25 12:12

Mr Nice


1 Answers

without seeing your code we can't help you out but from your question i can figure out the problem, this solution may help you out.

create stack such that

private static Stack<Fragment> myFragStack;
myFragStack = new Stack<Fragment>();

//To Load the fragment

public void loadFragment(Fragment fragment){
 FragmentManager fm = getSupportFragmentManager();
 FragmentTransaction ft = fm.beginTransaction();
 myFragStack.lastElement().onPause();
 ft.hide(myFragStack.lastElement());
 myFragStack.push(fragment);
}

//onBackPressed

public void onBackPressed() {
 FragmentManager fm = getSupportFragmentManager();
 FragmentTransaction ft = fm.beginTransaction();

 if (myFragStack.size() > 1) {
    ft.remove(myFragStack.pop());
    myFragStack.lastElement().onResume();
    ft.show(myFragStack.lastElement());
    ft.commit();
 }
}

It's a sample code.. you can change it as per your requirement. ft.replace() will completely remove the view & will lose the context so you can't maintain your list state, but using stacks maintaining fragments with hide-show will solve your problem.

like image 191
Zeeshan Saiyed Avatar answered Jan 01 '26 06:01

Zeeshan Saiyed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!