Reputation: 1549
I wonder whether I can manage fragments like Activity.
I implemented tab function with fragment(in fact, I couldn't get result from startActivityForResult
using TabHost
), and I wanna call each fragment when tab menu selected saving its previous view like using intent with FLAG_ACTIVITY_REORDER_TO_FRONT
. Whenever I replace fragment, program always create new fragment.
Any idea?
Thanks in advance.
ps. I tried to use savedInstanceState
, but Bundle only provides putInt
, putString
, putBundle
, etc. Is it possible to save view or other objects?
@PatrickBoos
Here is my code. After declare FragmentManager fm
and FragmentTransaction ft
,
AFragment fragment = AFragment.getInstance();
if (!fragment.isAdded())
ft.replace(res, fragment, tag);
ft.commit();
and AFragment.newInstance() is implemented as,
AFragment mThis;
public static AFragment getInstance() {
if (mThis == null)
mThis = new AFragment();
return mThis;
}
Upvotes: 3
Views: 2520
Reputation: 11230
Try using something similar to the code below to reuse a fragment
ContactListFragment contactListFragment =
(ContactListFragment)getFragmentManager().findFragmentByTag("ContactList");
if(contactListFragment == null){
contactListFragment = new ContactListFragment();
}
ft.replace(R.id.fragment_container, contactListFragment,"ContactList";
ft.commit();
Upvotes: 4