Alternative for the onResume() during Fragment switching
Asked Answered
M

6

31

onResume() method won't get called when we switch between fragments more than one time. So, is there any better way to handle resume operation?

Mutule answered 24/7, 2013 at 22:7 Comment(2)
What do you mean by switching between fragments?Pollaiuolo
Ex: Activity 'A' loads a fragment 'X' and some button click will switch fragment 'X' with 'Y'. Then, if you press back onResume() of fragment 'X' won't be called.Mutule
M
3

I think, I have found the answer. Here is the link which will force onResume() of the fragment to be called every time the fragment becomes visible.
Fragments onResume from back stack

Mutule answered 24/7, 2013 at 22:25 Comment(0)
D
41

Code follows:

Step: 1

Create Interface:

public interface YourFragmentInterface {
    void fragmentBecameVisible();
}

Step: 2

Attach Listner In setOnPageChangeListener:

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) {
            YourFragmentInterface fragment = (YourFragmentInterface) mPagerAdapter.instantiateItem(mViewPager, position);
            if (fragment != null) {
                fragment.fragmentBecameVisible();
            } 
        }

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

Step: 3

Implement Interface In Your Fragment:

public class yourActivity extends SherlockFragment implements YourFragmentInterface{
    @Override
    public void fragmentBecameVisible() {
          System.out.println("TestFragment");
    }
}

Implement this listner in all yor fragment activity fragmentBecameVisible() this method call during Fragment switching.

Thanks.

Discordancy answered 14/5, 2014 at 6:59 Comment(1)
actually you can just call YourFragmentInterface fragment = (YourFragmentInterface) mPagerAdapter.instantiateItem(mViewPager, position); if (fragment != null) { fragment.onResume(); }Eby
H
5

You can simply simulate onResume() for each fragment by using an interface!!!

1- create an interface named FragmentLifecycle , the code is as follows:

public interface FragmentLifecycle {
   public void onResumeFragment();
}

2- Let each Fragment implement the interface:

public class FragmentOne extends Fragment implements FragmentLifecycle

3- Implement interface methods in each fragment:

@Override
public void onResumeFragment() {
  Log.i(TAG, "onResumeFragment()");
  Toast.makeText(getActivity(), "onResumeFragment():" + TAG,Toast.LENGTH_SHORT).show(); 
}

4- Call interface methods on ViewPager page change:

viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {

            FragmentLifecycle fragmentToShow = (FragmentLifecycle)adapter.getItem(position);
            fragmentToShow.onResumeFragment();
        }
    });

Enjoy!

Holtz answered 31/8, 2016 at 7:44 Comment(3)
onResumeFragment doesn't have to be public when it's declared. Sorry for nit-picking :)Veneering
adaper.getItem() is designed to be called by the system. If you call getView() in onResumeFragment , it will return null. Please check out this answer: https://mcmap.net/q/57287/-retrieve-a-fragment-from-a-viewpagerVeneering
I added if (position == fragmentPos) and then call this fragment.Tomkins
M
3

I think, I have found the answer. Here is the link which will force onResume() of the fragment to be called every time the fragment becomes visible.
Fragments onResume from back stack

Mutule answered 24/7, 2013 at 22:25 Comment(0)
P
2

You could do resume work by provide a public method on every fragment when page selected, I give you a example:

public class MainActivity extends FragmentActivity {
private TabHost mTabHost;
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;

private ArrayList<Fragment> mFragments;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mTabHost = (TabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup();

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);

    mFragments = new ArrayList<Fragment>();
    mFragments.add(new TestFragment1());
    mFragments.add(new TestFragment2());
    mFragments.add(new TestFragment3());

    mTabsAdapter.addTab(mTabHost.newTabSpec("fragment1").setIndicator("fragment1"));
    mTabsAdapter.addTab(mTabHost.newTabSpec("fragment2").setIndicator("fragment2"));
    mTabsAdapter.addTab(mTabHost.newTabSpec("fragment3").setIndicator("fragment3"));

    if (savedInstanceState != null) {
        mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("tab", mTabHost.getCurrentTabTag());
}

private void refreshPage(int i) {
    Fragment fragment = mFragments.get(i);

    switch (i) {
        case 0:
            ((TestFragment1) fragment).refreshView();
            break;
        case 1:
            ((TestFragment2) fragment).refreshView();
            break;
        case 2:
            ((TestFragment3) fragment).refreshView();
            break;
    }
   }

class TabsAdapter extends FragmentPagerAdapter implements TabHost.OnTabChangeListener,
        ViewPager.OnPageChangeListener {
    private final Context mContext;
    private final TabHost mTabHost;
    private final ViewPager mViewPager;

    public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
        super(activity.getSupportFragmentManager());
        mContext = activity;
        mTabHost = tabHost;
        mViewPager = pager;
        mTabHost.setOnTabChangedListener(this);
        mViewPager.setAdapter(this);
        mViewPager.setOnPageChangeListener(this);
    }

    public void addTab(TabHost.TabSpec tabSpec) {
        tabSpec.setContent(new DummyTabFactory(mContext));
        mTabHost.addTab(tabSpec);
        notifyDataSetChanged();
    }

    @Override
    public Fragment getItem(int i) {
        return mFragments.get(i);
    }

    @Override
    public void onPageScrolled(int i, float v, int i2) {
    }

    @Override
    public void onPageSelected(int i) {
        TabWidget widget = mTabHost.getTabWidget();
        int oldFocusability = widget.getDescendantFocusability();
        widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        mTabHost.setCurrentTab(i);
        widget.setDescendantFocusability(oldFocusability);
        refreshPage(i);
    }

    @Override
    public void onPageScrollStateChanged(int i) {
    }

    @Override
    public void onTabChanged(String s) {
        int postion = mTabHost.getCurrentTab();
        mViewPager.setCurrentItem(postion, true);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    class DummyTabFactory implements TabHost.TabContentFactory {
        private final Context mContext;

        public DummyTabFactory(Context context) {
            mContext = context;
        }

        @Override
        public View createTabContent(String s) {
            View v = new View(mContext);
            v.setMinimumWidth(0);
            v.setMinimumHeight(0);
            return v;
        }
    }
}
}

and then you write your Fragment like this:

public class TestFragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.main, container, false);
}

public void refreshView() {
    //do whatever you want
}
}
Poisoning answered 24/7, 2013 at 22:31 Comment(0)
G
1

You can try this,

Step1: Override the Tabselected method in your activity

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in
    // the ViewPager.
    try {
    if(MyEventsFragment!=null && tab.getPosition()==3)
    {
        MyEvents.fragmentChanged();
    }
    }
    catch (Exception e)
    {

    }
    mViewPager.setCurrentItem(tab.getPosition());
}

Step 2: Using static method do what you want in your fragment,

public static void fragmentChanged()
{
    Toast.makeText(actvity, "Fragment Changed", Toast.LENGTH_SHORT).show();
}
Gainey answered 20/1, 2016 at 12:18 Comment(0)
T
0

I have solved this problem using fragment Override method :

 @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        if (getView() != null) {
            // your code goes here
        }
    }
}

Note: In the Viewpager first fragment setUserVisibleHint called before onCreateView so you need to handle this.

handle setUserVisibleHint called before onCreateView in Fragment

Twofaced answered 3/12, 2015 at 13:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.