Static Objects in Activities with View Pagers

1

I have an activity with a view pager, and this controls 3 fragments, f1, f2, f3. Fragment f1 shows items added by the user, fragment f2 loads all items from an external server, showing them in a list, and finally fragment f3 shows the items that the user decided to save. The items saved by the user are saved in txt, so they do not need access to the server.

The problem : Whenever the user saves an item, I need to add a markup on the selected item in f2, and automatically add it to f3, and the same happens when the user unchecks f3 and the item needs to be updated in f2, but in this case only the layout, since it has nothing to do with external connections.

The solution created by me : Leave public and static adapters in the activity and create methods within it that update the adapters whenever there is an action, so I had to create a class that extends the class Application , to create a global context.

Doubt : It is not good to create static contexts because of memory leak problems, but I think this should happen because keeping code working during other activities really should weigh. But using this solution between fragments, since these are always running in the foreground, can also bring risks of memory leakage? Note that I only use the static context in this activity so that the adapters can be updated by other fragments.

Thank you in advance!

    
asked by anonymous 14.09.2016 / 15:27

1 answer

0

There are a few ways to solve this problem for you. An alternative:

Create an interface

public interface MeuFragmentInterface {
    void fragmentBecameVisible();
}

Attach listener at setOnPageChangeListene

mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(final int position, final float v, final int i2) {
        }

        @Override
        public void onPageSelected(final int position) {
            MeuFragmentInterface fragment = (MeuFragmentInterface) mPagerAdapter.instantiateItem(mViewPager, position);
            if (fragment != null) {
                fragment.fragmentBecameVisible();
            } 
        }

        @Override
        public void onPageScrollStateChanged(final int position) {
        }
    });

Implementing Interface in your Fragment

public class MinhaActivity extends Fragment implements MeuFragmentInterface{
    @Override
    public void fragmentBecameVisible() {
          System.out.println("TestFragment");
    }
}

So you can call your method during the action of fragment .

Details

onPause () is not called on backstack
14.09.2016 / 16:03