zoukankan      html  css  js  c++  java
  • ViewPager+Fragment实现懒加载

    主要实现是复写Fragment下面这个方法,isVisibleToUser这个参数下面有解释:

    /**
    * Set a hint to the system about whether this fragment's UI is currently visible
    * to the user. This hint defaults to true and is persistent across fragment instance
    * state save and restore.
    *
    * <p>An app may set this to false to indicate that the fragment's UI is
    * scrolled out of visibility or is otherwise not directly visible to the user.
    * This may be used by the system to prioritize operations such as fragment lifecycle updates
    * or loader ordering behavior.</p>
    *
    * @param isVisibleToUser true if this fragment's UI is currently visible to the user (default),
    * false if it is not.
    */
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (!mUserVisibleHint && isVisibleToUser && mState < STARTED) {
            mFragmentManager.performPendingDeferredStart(this);
        }
        mUserVisibleHint = isVisibleToUser;
        mDeferStart = !isVisibleToUser;
    }
    

    注意,这个方法并不是fragment生命周期的一部分,而是Fragment与Viewpager一起使用时,ViewPager设置适配器--FragmentPagerAdapter调用的:

    @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if (mCurTransaction == null) {
                mCurTransaction = mFragmentManager.beginTransaction();
            }
    
            final long itemId = getItemId(position);
    
            // Do we already have this fragment?
            String name = makeFragmentName(container.getId(), itemId);
            Fragment fragment = mFragmentManager.findFragmentByTag(name);
            if (fragment != null) {
                if (DEBUG) Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment);
                mCurTransaction.attach(fragment);
            } else {
                fragment = getItem(position);
                if (DEBUG) Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment);
                mCurTransaction.add(container.getId(), fragment,
                        makeFragmentName(container.getId(), itemId));
            }
            if (fragment != mCurrentPrimaryItem) {
                fragment.setMenuVisibility(false);
                fragment.setUserVisibleHint(false);
            }
    
            return fragment;
        }
    

     实现适配器的时候,注意记得调用super就OK,不然这个方法不能触发。

  • 相关阅读:
    女子腰背疼痛案
    老人心悸心膝部无力屈伸不利案
    经方生姜泻心汤临床应用发挥
    电话求诊易误治
    女子乳房结块案
    小儿手足口案
    门纯德老先生经验
    男子肋部掣痛案
    加味潜降汤治疗阴虚阳亢之眩晕(来自网络)
    三叉神经痛与芎胡六虫汤
  • 原文地址:https://www.cnblogs.com/aprz512/p/4931064.html
Copyright © 2011-2022 走看看