Search code examples
javaandroidandroid-fragmentsandroid-lifecyclefragment-lifecycle

Issues with multiple instances of same Fragment in ViewPager?


Context: SubFragment1

Desired result: In onRefresh I want x to == z, in the example z is 1.

Problematic Result:

My Result

Solution Removing the multiple instances of SubFragment1 FragmentPagerAdapter

@Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new SubFragment1(...);
            case 1:
                return new SubFragment1(...);
            case 2:
                return new SubFragment1(...);
            default:
                return null;
        }
    }

Question: Any idea how using multiple instances of one fragment within a viewPager, would break break the fragment's logic or standard lifecycle behaviour? Nothing was static, variables were private.


Solution

  • Yeah, buddy, I was in such mess once.

    So what I did was, I used Five instances of same SubFragment and boy I was in trouble. Basically I had Five different screens with similar functionality(responsibility) but almost the same layout(UI design). As a result, I decided to use the same SubFragment just to promote the principle of Code Reusability.

    Initially, the requirements were small and everything was smooth, but later as changes(requirements) kept on piling I had nightmares managing them.

    Let me give you an example:

    So let's say there is a method checkLocationAndNotify() which will check if a location is available and will show a Dialog if no location was found.

    Now I wanted this method to be called only when my third instance of SubFragment would open on ViewPager(User Swipes and reach third Child on ViewPager).

    So I placed this method call in the onViewCreated() lifecycle method of SubFragment. Boom this was the first of my troubles. As soon as the user opened any of the ViewPager child, irrespective of the instance of SubFragment this method was called and kept showing LocationDialog every time.

    To resolve this, I had to put a check with respect to childPosition inside ViewPager. Also, I had to repeat this wherever I wanted some logic to work only on a certain instance of SubFragment.

    Golden Advice:

    If dealing with Fragments(even with slightly different responsibility) that too inside ViewPager please use different Fragments and promote the Single Responsibility principle over Code Reusability.