Usé un enfoque híbrido para fragmentos que contienen una vista de lista. Parece ser rentable ya que no reemplazo el fragmento actual, sino que agrego el nuevo fragmento y oculto el actual. Tengo el siguiente método en la actividad que aloja mis fragmentos:
public void addFragment(Fragment currentFragment, Fragment targetFragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(0,0,0,0);
transaction.hide(currentFragment);
// use a fragment tag, so that later on we can find the currently displayed fragment
transaction.add(R.id.frame_layout, targetFragment, tag)
.addToBackStack(tag)
.commit();
}
Utilizo este método en mi fragmento (que contiene la vista de lista) cada vez que se hace clic / se toca un elemento de la lista (y, por lo tanto, necesito iniciar / mostrar el fragmento de detalles):
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
SearchFragment currentFragment = (SearchFragment) fragmentManager.findFragmentByTag(getFragmentTags()[0]);
DetailsFragment detailsFragment = DetailsFragment.newInstance("some object containing some details");
((MainActivity) getActivity()).addFragment(currentFragment, detailsFragment, "Details");
getFragmentTags()devuelve una matriz de cadenas que uso como etiquetas para diferentes fragmentos cuando agrego un nuevo fragmento (vea el transaction.addmétodo en el addFragmentmétodo anterior).
En el fragmento que contiene la vista de lista, hago esto en su método onPause ():
@Override
public void onPause() {
// keep the list view's state in memory ("save" it)
// before adding a new fragment or replacing current fragment with a new one
ListView lv = (ListView) getActivity().findViewById(R.id.listView);
mListViewState = lv.onSaveInstanceState();
super.onPause();
}
Luego, en onCreateView del fragmento (en realidad en un método que se invoca en onCreateView), restauro el estado:
// Restore previous state (including selected item index and scroll position)
if(mListViewState != null) {
Log.d(TAG, "Restoring the listview's state.");
lv.onRestoreInstanceState(mListViewState);
}