基类+Fragment懒加载

  • BaseFragment—基类
package com.example.lianxi01_fragmen.base;

import android.os.Bundle;
import android.support.annotation.NonNull;
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;

/**
 * @Auther: 不懂
 * @Date: 2019/1/11 14:59:42
 * @Description:
 */
public abstract class BaseFragment extends Fragment {

    private boolean isViewCreated;//视图是否已经创建
    private boolean isUiVisible;//该fragment是否对用户可见

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), getResID(), null);
        //布局
        ivitView(view);
        isViewCreated = true;
        //数据
        lazyLoad();
        return view;
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isUiVisible = true;
            lazyLoad();
        }else{
            isUiVisible = false;
        }
    }

    private void lazyLoad() {
        //这里进行双重标记判断,是因为setUserVisibleHint会多次回调,
        // 并且会在onCreateView执行前回调,必须确保onCreateView加载完毕且页面可见,才加载数据
        if (isViewCreated && isUiVisible) {
            lazyLoadData();
            //数据加载完毕,恢复标记,防止重复加载
            isViewCreated = false;
            isUiVisible = false;

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isViewCreated = false;
        isUiVisible = false;
    }

//数据
    public abstract void lazyLoadData();
//id
    public abstract int getResID();
//布局
    public abstract void ivitView(View view);

}

  • 继承BaseFragment的类
package com.example.lianxi01_fragmen.fragmen;

import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lianxi01_fragmen.R;
import com.example.lianxi01_fragmen.base.BaseFragment;

/**
 * @Auther: 不懂
 * @Date: 2019/1/11 15:02:15
 * @Description:
 */
public class Fragments extends BaseFragment {


    private TextView tv;

    @Override
    public void lazyLoadData() {
        int position = getArguments().getInt("position");
        Toast.makeText(getActivity(), position + "", Toast.LENGTH_SHORT).show();
        tv.setText(position + "");
    }

    @Override
    public int getResID() {
        return R.layout.fragments;
    }

    @Override
    public void ivitView(View view) {
        tv = view.findViewById(R.id.tv);
    }

}

你可能感兴趣的:(Fragment)