0

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

Thomas Dang
  • 201
  • 3
  • 4
  • 14

1 Answers1

1

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.

harveyslash
  • 5,906
  • 12
  • 58
  • 111
  • Thanks for your answer, right now I need to run some tasks continuously, if I implements those task on fragment, would it stop when I change tabs to other fragment as well? Will it be good idea to do it all on MainActivity and only dsiplay it on different fragment, ot to implements those task on the fragments themselves. – Thomas Dang Jul 16 '14 at 04:40
  • if you want to run some tasks continuously , take a look at services. That will be the best way to go about it http://developer.android.com/guide/components/services.html . and accept/upvote if you find the answer useful – harveyslash Jul 16 '14 at 04:51
  • as for your question, if you do not want to use service , the 'task' of the fragment will continue running as long as you dont add the fragment to the backstack, or press the back button. – harveyslash Jul 16 '14 at 04:54