ViewPager+Fragment 数据懒加载、页面可见切换回调

package com.wangsz.myapplication.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by admin on 2017/7/5.
 */
public abstract class BaseFragment extends Fragment {

    protected String TAG = "BaseFragment";

    protected View mView;

    private boolean hasLoadData = false; // 是否已加载数据

    protected abstract void inflateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate()");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView()");
        if (mView == null) {
            inflateView(inflater, container, savedInstanceState);
        }

        return mView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        //如果setUserVisibleHint()在mView 创建前调用时,那么
        //就等到rootView创建完后才回调onFragmentVisibleChange(true)
        //保证onFragmentVisibleChange()的回调发生在mView 创建完成之后,防止mView == null
        if (getUserVisibleHint()) {
            if (!hasLoadData) {
                // 一般是第一次打开TabActivity页面时,当前Fragment会走这里
                loadData();
                hasLoadData = true;
            }
            onFragmentVisibleChange(true);
        }
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // setUserVisibleHint在初始化Fragment的时候也会调用,且在onCreateView之前,所以mView会为null
        // mView是否初始化标志,防止回调函数在mView为空的时候触发
        if (mView == null) {
            return;
        }

        if (!hasLoadData && isVisibleToUser) {
            loadData();
            hasLoadData = false;
        }

        onFragmentVisibleChange(isVisibleToUser);

    }


    /**
     * fragment可见状态发生变化时的回调。处理一些UI变化等?
     *
     * @param isVisible true  不可见 -> 可见
     *                  false 可见  -> 不可见
     */
    protected void onFragmentVisibleChange(boolean isVisible) {
        Log.d(TAG, "页面可见切换 onFragmentVisibleChange = " + isVisible);

    }

    /**
     * 在fragment首次可见时回调,可在这里进行加载数据,
     * 用hasLoadData保证只在Fragment第一次可见时才会加载数据,
     * 这样就可以防止每次进入都重复加载数据
     */
    protected void loadData() {
        Log.d(TAG, "页面第一次可见,loadData");

    }

}


    原文作者:zsgnaw
    原文地址: https://www.jianshu.com/p/aa10a5e6d346
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞