Since TabActivity is deprecated I need to find a way to do it with Fragments. I have worked with Fragments before I know how it works but I need a guide to create my tab host with FragmentActivities. I have found a couple of examples on the internet, and they are all about putting fragments into a container for the tabs.
What I want is to put FragmentActivities for each tab. Because in my application I will be using 4 tabs and each of the tabs have really complex content in it. As a result, I need to have a FragmentActivity for each tab to manage the Fragments that I will put under each tab within a separated container.
SOLUTION:
After answers and searching on internet I ended up with a Solution. According to the solution I have found, I keep track of Fragments in separated stack for each tab under tab host. Here is my GitHub repository, I created a small sample app for this problem.
If you don’t want to use
TabActivity– forget about puttingFragmentActivitiesinto tab’s content.I remind that you can use
TabWidgetwithoutTabActivity. So you can try this solution:FragmentActivity.TabWidgetintoFragmentActivity‘s layout. MakeTabWidget‘s content’s height = 0.TabWidgetin XML declare container for youFragments (FrameLayoutfor example).FragmentActivityjust handle which tab is selected (TabHost.OnTabChangeListener) and put neededFragmentinto container.Or you can create
FragmentActivitywithTabWidget, and instead of switchingFragments you can directly putFragments into each tab’s content.For example if you have 3 tabs and 3 fragments try what i do. Call
showFragmentXwhen you need to change one fragment to another.If you do so your
fragmentXvariables will not be deleted each time you put them infragment_container. They will live while yourFragmentActivitylive. Take look at fragments lifecycle.Only
OnCreateViewandonDestroyViewmethods of fragments will call again and again while youreplaceone fragment to another.Also Fragments has their
onSaveInstanceStatemethod where you can save the state of your fragment. For example: user typed his name in fragment1’s editText. If you want to keep this data(name string) while user discover other fragments you should1.save name string in fragment1’s
onSaveInstanceStatemethod2. into fragment1’s
onCreateViewmethod check savedInstanceState bundle, if it’s not null – fill edittext with string that you get from bundle.}
You can check data before saving. I hope my point is clear now.
Also if you call
setRetainInstance(true)inonCreateView()method of yourfragment– system will try to save the state of fragment (with all input data). link to description