androidandroid-fragmentsxml-layout

Reusing Fragment or layout files


I am making an English education app that has an activity that uses viewPager to return a number of fragments. The app will have additional units which use additional activities that use viewPager to return the same fragments(minus some word changes and order changes). What is the best way to reuse the fragments? Should I just implement the fragments in another activity? And if so, is it possible to have problems if a fragment is implemented in a new activity when the same fragment is already used by another activity in the back stack? Or is there another way I can reuse either my fragments or my layout files? Thanks in advance.


Solution

  • Reusability is one of the main benefits of using Fragments, so you should certainly try and reuse them whenever possible. From the Android documentation (https://developer.android.com/guide/components/fragments.html)

    You can (...) reuse a fragment in multiple activities

    Since Android will create a new instantiation of your Fragment whenever you reuse it, there should be no risk of clashing with an existing Fragment (as long as you don't use static variables that are shared between them).