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.
-
Please elaborate more. You might wanna read this (http://stackoverflow.com/questions/7951730/viewpager-and-fragments-whats-the-right-way-to-store-fragments-state) Also, there is no issue if 2 instances of a fragment are available in back stack. They were created for that purpose only. – Gaurav Chauhan Jan 30 '17 at 16:14
2 Answers
Yes you can reuse your fragments and activities for many times. First of all, your activities must be a container of fragments, try not to give a lot of responsibility to your activities. You can create one BaseActivity and put one layout (For example Relative Layout) as a fragment container, then in every activity that you implement from base class you can call your base replace fragment method.
private void changeFragment(Fragment targetFragment){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
Here you should change the "fragment' TAG for every different Fragment then when you get the TAG, in the new Fragment you can recognize which fragment is that. So better doing this part abstract method.

- 4,596
- 8
- 33
- 44

- 197
- 6
-
Thanks. This answers my question, too. I will definitely keep in mind the replacing fragments way for future reference. Sorry I can't accept two answers. – Ntwofive Jan 31 '17 at 15:24
Reusability is one of the main benefits of using Fragment
s, 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).

- 2,717
- 3
- 16
- 22
-
Thanks, that is what i wanted to know. I can now continue making my app knowing that i am not going to run into problems later – Ntwofive Jan 31 '17 at 15:19