Switching from TabHost to Fragments with Viewpager: Where to put all my Code
Asked Answered
K

1

6

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?

Kuo answered 20/1, 2012 at 18:39 Comment(0)
H
3

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.

Hebe answered 1/2, 2012 at 0:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.