Android : swap between grid and list fragments

on Thursday, September 11, 2014


The main section of my screen layout shows a set of items. The use can choose if a grid or a list should be shown. Therefore I implemented two fragements (for list and grid) that are then shown inside the placeholder (main section of the main layout).


But now I wonder how to reuse the fragements in order to have the last scrolling position etc. If I remember the fragment in a private field instead of re-creating it, then the view remains empty.


Any idea?



public void onShowGrid(View view) {

// how to re-use instead of re-create
fragmentGrid = new PreviewGridFragment();

this.getFragmentManager().beginTransaction()
.replace(R.id.preview_fragment, fragmentGrid)
.addToBackStack(null).commit();
}

public void onShowList(View view) {

// how to re-use instead of re-create
fragmentList = new PreviewListFragment();

this.getFragmentManager().beginTransaction()
.replace(R.id.preview_fragment, fragmentList)
.addToBackStack(null).commit();
}


Dynamic Fragments


0 comments:

Post a Comment