ViewPager+Fragment 懒加载 (性能优化)

懒加载原则:可见时加载,不可见就不加载
java:

/**
 * @author damei
 * @Time 2020/2/28 10:26
 * @Description:
 */
public abstract class LazyFragment extends Fragment {


    private static final String TAG = "LazyFragment";
    private View mView;
    private boolean isViewCreated = false;//当前view是否已经被创建
    private boolean currentViewState = false;//因为viewPager添加item的时候会触发setUserVisibleHint(false)
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(mView==null){//如果view已经被创建就不必要创建了
            mView = inflater.inflate(getLayoutResource(),container,false);
        }
        initView(mView);
        isViewCreated = true;//表示当前View已经被创建
        if(currentViewState){
            dispatchFragmentState(true);
        }
        Log.i(TAG, "onCreateView: ");
        return mView;
    }

//setUserVisibleHint() 设置用户是否可见
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if(isViewCreated){//view被创建后才进行分发否则会NullPointException
            if(isVisibleToUser && !currentViewState){//当前item由不可见变为可见加载
                dispatchFragmentState(true);
            }else if(!isVisibleToUser && currentViewState){//当前item由可见变为可见不分发
                dispatchFragmentState(false);
            }
        }
        Log.i(TAG, "setUserVisibleHint: 开始分发事件");
    }

    private void dispatchFragmentState(boolean isVisible){
        if(isVisible==currentViewState){//如果状态保持一致就没必要重复加载了
            return;
        }
        currentViewState = isVisible;//记录当前item状态
        if(isVisible){
            onFragmentLoad()//加载页面;
            Log.i(TAG, "dispatchFragmentState: 开始加载");
        }else{
            onFragmentLoadStop()//停止加载页面;
            Log.i(TAG, "dispatchFragmentState: 停止加载");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: ");
        //按home键或fragment跳转activity情况考虑
        //重新可见加载
        if(currentViewState){
            dispatchFragmentState(true);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i(TAG, "onPause: ");
         //按home键或fragment跳转activity情况考虑
        //不可见停止加载
        if(currentViewState){
            dispatchFragmentState(false);
        }
    }

    protected void onFragmentLoad() {}
    protected void onFragmentLoadStop(){}

    protected abstract void initView(View view);
    protected abstract int getLayoutResource();
}

你可能感兴趣的:(性能优化)