Until now I've used TabHost
for my App to create 3 Tabs. Each Tab is represented by an Activity in which I get the layout via setContentView(R.layout.something)
from an XML file.
So 3 Tabs, 3 Activities and 3 XML files.
Now I've stumbled upon fragments, which are the new and better way to go, so here is my question.
Fragments handle the UI, so create 3 Fragments which are handled by FragmentPagerAdapter
. Inside each Fragment I create the Content via XML files.
But where do I put all the code about which button does what, read from database or write to it etc. So far that's all been in each Activity that was loaded by the Tabhost
.
Do I put all that code into the onCreate()
etc. methods of each fragment or is there a better and cleaner way to do it?
The approach you propose is pretty much fine!
In terms of what to do where, I'd recommend that you do anything to create/alter the the UI of a page (fragment) in onCreateView() of each fragment, and any logic (reading databases etc) in onActivityCreated(). I'd recommend steering clear of onCreate() in a fragment, because this is called before it is associated with an Activity (preventing you doing thigs such as managed queries to contentproviders). Button click listeners could be defined either in onCreateView or onActivityCreated().
Anything more specific, let me know. Dont forget, standard Pagers don't include a row of tab titles/icons, but Google ViewPagerIndicator and you'll find a library which you can use to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With