Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 885
majinboo Avatar asked Jan 20 '12 18:01

majinboo


1 Answers

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.

like image 195
Alex Curran Avatar answered Oct 11 '22 17:10

Alex Curran