Search code examples
androidandroid-activityandroid-fragmentsandroid-pageradapter

Fragment Implementation


I am new to Android Coding so this might seems to be simple, but please help me solve my confusion about Fragment:

  1. Can a fragment "do stuff" like Activities (like call some methods, run some schedule task. Or it is more like a view to display the info given by the parent Activity

  2. Can 2 fragments run at the same time, for example, if I have 1 fragment runs a scheduled task every 10 ms and 1 fragment runs another scheduled task every 20 ms, can they run together?

  3. I use FragmentPagerAdapter to create different tabs, each of the tabs holds 1 fragment, will switching between tabs pause or stop my fragment? Can I switch to tab 2 and make the fragment on tab 1 still running?

  4. How can a Fragment communicate with other Fragment (with same parent Activity), for example fragment 2 get sensor information and if it is larger than some threshold it flags fragment 1 to do some thing?

Please enlighten me, thank you very much


Solution

  • You can think of Fragments like sub activities. They can almost do everything that activities can. They just extend Fragment, so the code might be a little different. They can have all the views that an activity has.

    For your scheduling part, you will have to switch the fragments (so this cant happen in the background), but if you want to switch while the app is on, it is possible.

    For the third point, look at the image I have attached(fragment lifecycle) enter image description here

    And this is about communicating with other fragments.