OnResume() not called in Fragment using tabLayout and ViewPager

Anto picture Anto · Feb 16, 2016 · Viewed 9.4k times · Source

i'm developing an app using tabLayout.

I've a problem: When I try to reactivate a Fragment, the method OnResume is non called.

This is my activity:

 private void init() {
    fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Nuovo Ticket", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });


    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    final PagerAdapter adapter = new PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);

    tabLayout.setupWithViewPager(viewPager);
}

I use a FragmentStatePagerAdapter like this:

public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;

public PagerAdapter(FragmentManager fm, int NumOfTabs) {
    super(fm);
    this.mNumOfTabs = NumOfTabs;
}

@Override
public Fragment getItem(int position) {

    switch (position) {
        case 0:
            return new LavorazioneFragment();
        case 1:
            return new PendingFragment();
        case 2:
            return new StoriciFragment();
        default:
            return null;
    }
}

@Override
public int getCount() {
    return mNumOfTabs;
}

}

When i reactivate the TAB1 Fragment from TAB3 Fragment (the last one), the OnResume Method is called. But, for example,

When I try to reactivate the first tab from the second, never called.

Answer

Anto picture Anto · Feb 17, 2016

I've solved the problem. I use setUserVisibleHint(boolean isVisibileToUser) instead onResume(). Like this:

 @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(isVisibleToUser) {
        init();
    } else {

    }
}

Thank you all!