Home » Android » android – OnResume() not called in Fragment using tabLayout and ViewPager

android – OnResume() not called in Fragment using tabLayout and ViewPager

Posted by: admin May 14, 2020 Leave a comment

Questions:

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.

How to&Answers:

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!

Answer:

The accepted answer did not work for me. However, I found a solution to the problem.

Just initialise your FragmentStatePagerAdapter with the following constructor:

public MyPagerAdapter(FragmentManager fm, int behaviour) {
    super(fm, behaviour);
}

like this :

MyPagerAdapter myPagerAdapter = new MyPagerAdapter(getChildFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);