美文网首页
ViewPager + Fragment 延迟加载

ViewPager + Fragment 延迟加载

作者: Batashi | 来源:发表于2018-06-06 15:25 被阅读0次

一、装载fragment的Activity:
FragActivity.java

package com.wei.wanandroid.activity.fragment;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.wei.wanandroid.R;
import com.wei.wanandroid.activity.BaseActivity;

import java.util.ArrayList;
import java.util.List;

public class FragActivity extends BaseActivity
{
    public static final int TAB_ONE = 0;
    public static final int TAB_TWO = 1;
    public static final int TAB_THREE = 2;
    private ViewPager mViewPager;
    private MainTabPagerAdapter mMainTabPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frag);
    }

    @Override
    public void initView() {
        mViewPager = findViewById(R.id.viewPager);
        mMainTabPagerAdapter = new MainTabPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mMainTabPagerAdapter);
        mViewPager.setCurrentItem(TAB_ONE);
        mViewPager.setOffscreenPageLimit(mMainTabPagerAdapter.getCount());
    }

    private class MainTabPagerAdapter extends FragmentPagerAdapter
    {
        private List<Fragment> mFragments;
        private FragmentManager mFragmentManager;

        public MainTabPagerAdapter(FragmentManager fm) {
            super(fm);
            mFragmentManager = fm;
            mFragments = new ArrayList<>();
        }

        @Override
        public Fragment getItem(int position)
        {
            Fragment fragment = null;
            switch (position)
            {
                case TAB_ONE:
                    fragment = new Fragment1();
                    break;

                case TAB_TWO:
                    fragment = new Fragment2();
                    break;

                case TAB_THREE:
                    fragment = new Fragment3();
                    break;

                    default:
            }
            mFragments.add(fragment);
            return fragment;
        }

        @Override
        public int getCount()
        {
            return 3;
        }
    }
}

二、各fragment的父类,LazyFragment.java。

package com.wei.wanandroid.activity.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;

import com.wei.wanandroid.activity.BaseFragment;

/**
 * 懒加载(延迟加载)
 *
 * @author: WEI
 * @date: 2018/6/5
 */
public abstract class LazyFragment extends BaseFragment {
    private boolean hasCreated = false, isFirstVisible = true, isFirstResume = true;

    /**
     * setUserVisibleHint()在Fragment实例化时会先调用一次,并且默认值是false,当选中当前
       显示的Fragment时还会再调用一次。
     * 此方法在fragment生命周期开始之前便被调用,运行在onAttach()之前。所以,它运行的时候,
       fragment都还没创建。
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        Log.e(TAG, "--- setUserVisibleHint ---, isVisibleToUser = " 
           + isVisibleToUser + ", hasCreated = " + hasCreated);
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser)
        {
            if (isFirstVisible) {
                isFirstVisible = false;
                // 之前还没初始化
                initPrepare();
            } else {
                // 已经初始化
                onLazyResume();
            }
        } else {
            if (hasCreated)
            {
                onLazyPause();
            }
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.e(TAG, "--- onActivityCreated ---");
        super.onActivityCreated(savedInstanceState);
        hasCreated = true;
        initPrepare();
    }

    @Override
    public void onResume()
    {
        Log.e(TAG, "--- onResume ---");
        super.onResume();
        if (isFirstResume)
        {  // 页面一加载的时候,所有fragment的生命周期都会执行到onResume。所以,第一次到
           // 这里的都停止,不再往后操作。
            isFirstResume = false;
            return;
        }
        Log.e(TAG, "onResume(), getUserVisibleHint() = " + getUserVisibleHint());
        if (getUserVisibleHint()) {
            // 用户可见状态
            onLazyResume();
        }
    }

    @Override
    public void onPause() {
        Log.e(TAG, "--- onPause ---");
        super.onPause();
        Log.e(TAG, "onPause(), getUserVisibleHint() = " + getUserVisibleHint());
        if (getUserVisibleHint()) {
            onLazyPause();
        }
    }

    private void initPrepare()
    {
        // 必须是用户可见状态并且fragment已经创建
        if (getUserVisibleHint() && hasCreated)
        {
            Log.e(TAG, "--- initPrepare ---");
            onFirstInit();
            onLazyResume();
        }
    }

    /**
     * 第一次fragment可见(进行初始化工作)
     */
    public abstract void onFirstInit();

    /**
     * fragment可见(onResume 回调)
     */
    public abstract void onLazyResume();

    /**
     * fragment不可见(onPause 回调)
     */
    public abstract void onLazyPause();
}

三、流程打印:
1.刚进入FragActivity :

10:56:24.271 6061-6061/com.wei.wanandroid E/MainActivity: onPause
10:56:24.298 6061-6061/com.wei.wanandroid E/FragActivity: onCreate
10:56:24.356 6061-6061/com.wei.wanandroid E/FragActivity: onStart
10:56:24.360 6061-6061/com.wei.wanandroid E/FragActivity: onResume
10:56:24.379 6061-6061/com.wei.wanandroid E/Fragment1: --- setUserVisibleHint ---, isVisibleToUser = false, hasCreated = false
10:56:24.380 6061-6061/com.wei.wanandroid E/Fragment2: --- setUserVisibleHint ---, isVisibleToUser = false, hasCreated = false
10:56:24.380 6061-6061/com.wei.wanandroid E/Fragment3: --- setUserVisibleHint ---, isVisibleToUser = false, hasCreated = false
10:56:24.380 6061-6061/com.wei.wanandroid E/Fragment1: --- setUserVisibleHint ---, isVisibleToUser = true, hasCreated = false
10:56:24.381 6061-6061/com.wei.wanandroid E/Fragment1: --- onAttach ---
- onCreate ---
10:56:24.381 6061-6061/com.wei.wanandroid E/Fragment2: --- onAttach ---
- onCreate ---
10:56:24.381 6061-6061/com.wei.wanandroid E/Fragment3: --- onAttach ---
- onCreate ---
10:56:24.382 6061-6061/com.wei.wanandroid E/Fragment1: --- onCreateView ---
10:56:24.396 6061-6061/com.wei.wanandroid E/Fragment1: --- onActivityCreated ---
- initPrepare ---
- onFirstInit() ---
- onLazyResume() ---
- onResume ---
10:56:24.396 6061-6061/com.wei.wanandroid E/Fragment2: --- onCreateView ---
10:56:24.400 6061-6061/com.wei.wanandroid E/Fragment2: --- onActivityCreated ---
10:56:24.400 6061-6061/com.wei.wanandroid E/Fragment3: --- onCreateView ---
10:56:24.403 6061-6061/com.wei.wanandroid E/Fragment3: --- onActivityCreated ---
10:56:24.403 6061-6061/com.wei.wanandroid E/Fragment2: --- onResume ---
10:56:24.403 6061-6061/com.wei.wanandroid E/Fragment3: --- onResume ---
10:56:24.476 6061-6113/com.wei.wanandroid D/OpenGLRenderer: endAllActiveAnimators on 0xcb3c1c00 (MenuPopupWindow$MenuDropDownListView) with handle 0xc9fc7340
10:56:24.749 6061-6061/com.wei.wanandroid E/MainActivity: onSaveInstanceState
10:56:24.752 6061-6061/com.wei.wanandroid E/MainActivity: onStop

2.切换到第二个fragment:

11:00:49.654 6061-6061/com.wei.wanandroid E/Fragment1: --- setUserVisibleHint ---, isVisibleToUser = false, hasCreated = true
11:00:49.655 6061-6061/com.wei.wanandroid E/Fragment1: --- onLazyPause() ---
11:00:49.655 6061-6061/com.wei.wanandroid E/Fragment2: --- setUserVisibleHint ---, isVisibleToUser = true, hasCreated = true
- initPrepare ---
11:00:49.656 6061-6061/com.wei.wanandroid E/Fragment2: --- onFirstInit() ---
- onLazyResume() ---

3.再回到第一个fragment:

11:03:02.823 6061-6061/com.wei.wanandroid E/Fragment2: --- setUserVisibleHint ---, isVisibleToUser = false, hasCreated = true
- onLazyPause() ---
11:03:02.824 6061-6061/com.wei.wanandroid E/Fragment1: --- setUserVisibleHint ---, isVisibleToUser = true, hasCreated = true
- onLazyResume() ---

四、总结:
懒加载技术要点在于对setUserVisibleHint(boolean isVisibleToUser)方法的处理时机的把握。该方法第一次调用时,FragmentonAttach(Context context)方法都还未执行,也就是说此时Fragment还没创建,此时什么事情也不能做。直到onActivityCreated(@Nullable Bundle savedInstanceState)执行完毕,且getUserVisibleHint()为真(Fragment可见)时才进行数据的加载,此时只加载当前可见的Fragment界面的数据,其它不可见的Fragment并未加载数据,从而提高数据展示速度,展示更好的用户体验效果。以后在各个Fragment之间切换时,都会在onLazyPause()onLazyResume()之间回调。

相关文章

网友评论

      本文标题:ViewPager + Fragment 延迟加载

      本文链接:https://www.haomeiwen.com/subject/vzbbsftx.html