Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnResume() not called in Fragment using tabLayout and ViewPager

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.

like image 390
Anto Avatar asked Feb 16 '16 15:02

Anto


1 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!

like image 185
Anto Avatar answered Dec 16 '22 19:12

Anto