Mr Nice
Mr Nice

Reputation: 524

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.

Upvotes: 3

Views: 3401

Answers (1)

Zeeshan Saiyed
Zeeshan Saiyed

Reputation: 466

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.

Upvotes: 2

Related Questions