简体   繁体   中英

How to Split Fragment Logic Out of MainActivity.java

I would like to add separate files for each fragment I want to add to my tabbed Android application. Each tab view should reference code contained in one of those separate files.

  1. Is this possible?
  2. Is it safe to split the logic completely out of the MainActivity class?
  3. Should I simply call their onCreate events within onCreate in MainActivity or is there a better way?

Any input is appreciated as this diverges significantly from what I've read and seems like it could cause a lot of unforeseen problems. Albeit it would be great to have this for readability.

  1. Not only is this possible, it's good practice. Typically, you create separate files for each of your classes. I understand your confusion, though, since the default "Tabbed Activity" project template puts the fragment logic in MainActivity . This isn't required.

  2. It is completely safe to separate the Fragment-specific logic into its own file.

  3. You shouldn't call onCreate yourself. The system does this for you.

I modified the "Tabbed Activity" template to use separate files for each tabbed fragment. Check it out here , and let me know if you have any other questions.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM