Switching from TabHost to fragments using Viewpager: where to put all my code

So far I have used TabHost for my application to create 3 tabs. Each tab is represented by Office, in which I get the layout through setContentView(R.layout.something) from an XML file. So, 3 tabs, 3 actions and 3 XML files.

Now I came across fragments that are a new and better way, so here is my question.

Fragments process the user interface, so create 3 fragments that are processed by the FragmentPagerAdapter . Inside each fragment, I create content through XML files.

But where do I put all the code about which button does what it reads from the database or writes to it, etc. So far, they have all been in every Activity uploaded by TabHost .

I put all this code in onCreate() methods, etc. for each fragment or is there a better and cleaner way to do this?

+6
source share
1 answer

The approach you offer is pretty great!

Regarding what to do, I would recommend you do something to create / change the user interface of the page (fragment) in onCreateView () of each fragment and any logic (read database, etc.) in onActivityCreated (). I would recommend disabling onCreate () in the fragment because it is called before it is associated with the Activity (preventing the execution of actions such as managed requests for content providers). Buttons for listening to buttons can be defined either in onCreateView or onActivityCreated ().

Anything more specific let me know. Do not forget that standard pagers do not include a number of tablet / icon names, but Google ViewPagerIndicator and you will find a library that you can use for this.

+3
source

Source: https://habr.com/ru/post/906500/


All Articles