This is the situation. I have a listview in a fragment A with an infinite list that is populated throught web service when user reach bottom.
Each item in the listview have a "View more" link that open a detailed fragment B for this item.
I'm using FragmentManager.replace() method and "addToBackStack". (I'm "replacing" and not "adding" because I have menu items in fragment A that I don't want to show in fragment B. I already tryed different ways with adding fragment instead removing and trying to hide menu items when opening fragment B that have worked, but ended in some other problems, so I prefer to use replace")
Supose that user is seeing item 25 in the list and then open detail fragment. When the user then hit the back button, I want the user to continues viewing the list in the same position exactly.
This was easy to make with "adding fragment" instead of "replacing" because the fragment was never removed. When using "replace" the fragment is removed and then when hit back it will render again (aka, will call onCreateView again)
But at this point, the view is already created for the fragment because FragmentManager.remove only remove view from the view hierarchy, but don't destroy the fragment. So I "theoretically" can do something like this:
if(view == null){
//Create view
view = (ViewGroup) inflater.inflate(R.layout.news_list, container, false);
}
return view;
But in this case it will result in an
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
So, my solution was the following:
if(view == null){
view = (ViewGroup) inflater.inflate(R.layout.news_list, container, false);
} else {
((ViewGroup) view.getParent()).removeView(view);
}
return view;
This is working for me, but I don't know if there will be some "hidden" errors beyond this solution that I'm not seeing right now.
I want to hear for your advices. Thanks in advance