简体   繁体   English

未使用 tabLayout 和 ViewPager 在 Fragment 中调用 OnResume()

[英]OnResume() not called in Fragment using tabLayout and ViewPager

i'm developing an app using tabLayout .我正在使用tabLayout开发应用程序。

I've a problem: When I try to reactivate a Fragment , the method OnResume is non called.我有一个问题:当我尝试重新激活FragmentOnResume调用OnResume方法。

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:我使用这样的 FragmentStatePagerAdapter:

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.当我从TAB3片段(最后一个)重新激活TAB1片段时,将OnResume方法。 But, for example,但是,例如,

When I try to reactivate the first tab from the second, never called.当我尝试从第二个选项卡重新激活第一个选项卡时,从未调用过。

I've solved the problem.我已经解决了这个问题。 I use setUserVisibleHint(boolean isVisibileToUser) instead onResume().我使用 setUserVisibleHint(boolean isVisibileToUser) 代替 onResume()。 Like this:像这样:

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

    }
}

Thank you all!谢谢你们!

The accepted answer did not work for me.接受的答案对我不起作用。 However, I found a solution to the problem.但是,我找到了解决问题的方法。

Just initialise your FragmentStatePagerAdapter with the following constructor:只需使用以下构造函数初始化您的 FragmentStatePagerAdapter:

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

like this :像这样 :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM