TabLayout+ViewPager+Fragment, 为什么Fragment不走onHiddenChanged方法

解决方案 »

  1.   

    因为Fragment都是被销毁后新建的,不是原来的
      

  2.   

    先设置viewpager的setOffscreenPageLimit为fragment的总数,防止fragment销毁,其次,切换fragment会调用setUserVisibleHint方法,而不是onHiddenChanged。具体看FragmentPagerAdapter中的代码,参考public abstract class FragmentPagerAdapter extends PagerAdapter {
            ……
            public Object instantiateItem(ViewGroup container, int position) {
            if(this.mCurTransaction == null) {
                this.mCurTransaction = this.mFragmentManager.beginTransaction();
            }        long itemId = this.getItemId(position);
            String name = makeFragmentName(container.getId(), itemId);
            Fragment fragment = this.mFragmentManager.findFragmentByTag(name);
            if(fragment != null) {
                this.mCurTransaction.attach(fragment);
            } else {
                fragment = this.getItem(position);
                this.mCurTransaction.add(container.getId(), fragment, makeFragmentName(container.getId(), itemId));
            }        if(fragment != this.mCurrentPrimaryItem) {
                fragment.setMenuVisibility(false);
                fragment.setUserVisibleHint(false);
            }        return fragment;
        }    public void destroyItem(ViewGroup container, int position, Object object) {
            if(this.mCurTransaction == null) {
                this.mCurTransaction = this.mFragmentManager.beginTransaction();
            }        this.mCurTransaction.detach((Fragment)object);
        }    public void setPrimaryItem(ViewGroup container, int position, Object object) {
            Fragment fragment = (Fragment)object;
            if(fragment != this.mCurrentPrimaryItem) {
                if(this.mCurrentPrimaryItem != null) {
                    this.mCurrentPrimaryItem.setMenuVisibility(false);
                    this.mCurrentPrimaryItem.setUserVisibleHint(false);
                }            if(fragment != null) {
                    fragment.setMenuVisibility(true);
                    fragment.setUserVisibleHint(true);
                }            this.mCurrentPrimaryItem = fragment;
            }
        }
    }
      

  3.   

    只有FragmentTransaction的show()和hide()方法才会调用onHiddenChanged()方法
      

  4.   

    getUserVisibleHint获得当前是否可见