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,不然这个方法不能触发。

  • 相关阅读:
    03JavaScript程序设计修炼之道 2019-06-23_15-50-11 验证码
    03JavaScript程序设计修炼之道 2019-06-23_15-21-11 全选和反选
    python进阶(10)迭代器
    python进阶(9)多线程
    python进阶(8)多进程
    python进阶(7)垃圾回收机制
    python进阶(6)深拷贝和浅拷贝
    python进阶(5)异常模块
    python进阶(4)文件操作
    python进阶(3)json文件与python字典的转化
  • 原文地址:https://www.cnblogs.com/aprz512/p/4931064.html
Copyright © 2011-2022 走看看