Android studio - tabbed activity how to reset fragment to default view?

759 views Asked by At

I have one fragment where are three (default) images and when user click on them, they will change to another. But when i swipe to another fragment and back to fragment with images there are not default ones as on the start. When I swipe two times so I will pass to another fragment (distance from original with images is 2 fragments) images are resetted to default. I was trying to implement setOffscreenPageLimit() from ViewPager and set it to 1, but minimum "length" when views in fragments are resetted is 2. How can I change that images to default manually after swipe action? Thank you.

Edit: I think that issue why onResume() is not working here: Fragment onResume not called

but i dont know what that means :/ I have three classes FragmentController.class, PagerAdapter.class and class of specific fragment for example FirstFragment.class. I don't know how connect these classes together.

1

There are 1 answers

10
jeprubio On BEST ANSWER

Check that you create the fragments in the getItem() method of the adapter and do not hold any reference to that fragments (only WeakReferences if necessary), otherwise the fragments could not be destroyed.

EDIT:

The first fragment is unloaded only when you are in the third one because setOffscreenPageLimit is at least 1 so a viewpager allways loads the fragments that are at both sides of the selected one.

What you could do is to update your adapter with this code to provide a getFragment(position) method:

private HashMap<Integer, WeakReference<Fragment>> fragmentReferences = new HashMap<>();

@Override
public Fragment getItem(int position) {
    Fragment fragment;
    switch (position) {
        case 0:
            fragment = FirstFragment.newInstance();
            break;
        // etc
    }
    fragmentReferences.put(position, new WeakReference<>(fragment));
    return fragment;
}

public Fragment getFragment(int position) {
    WeakReference<Fragment> ref = fragmentReferences.get(position);
    return ref == null ? null : ref.get();
}

After then you can get the selected fragment and call the method you want from the first fragment when a page is selected:

viewPager.setOnPageChangeListener(new OnPageChangeListener() {
    @Override
    public void onPageSelected(int currentPage) {
        if (currentPage == 0) {
            Fragment firstFragment = adapter.getFragment(0);
            if (firstFragment != null) {
                // This method resets the images of the first fragment
                ((FirstFragment) firstFragment).reset();
            }
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        // Do nothing
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        // Do nothing
    }
});