1. 实现懒加载的 fragment
/**
* Created by Administrator on 2017/4/16/016.
* Bruce Lee
* 备注:fragment 懒加载
*/
public abstract class LazyLoadFragment extends Fragment{
protected boolean isViewInitiated;
protected boolean isVisibleToUser;
protected boolean isDataInitiated;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
isViewInitiated = true;
prepareFetchData();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
this.isVisibleToUser = isVisibleToUser;
prepareFetchData();
}
//网络请求在这里进行
public abstract void fetchData();
public boolean prepareFetchData() {
return prepareFetchData(false);
}
public boolean prepareFetchData(boolean forceUpdate) {
/**
* 当前fragment对用户可见并且已经初始化并且还未加载数据
* 则调用fetchData方法,即在可这里进行网络加载数据
* 加载数据后使isDataInitiated为false确保不重复加载数据
*/
if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
fetchData();
isDataInitiated = true;
return true;
}
return false;
}
protected Fragment getRootFragment() {
Fragment fragment = getParentFragment();
while (fragment.getParentFragment() != null) {
fragment = fragment.getParentFragment();
}
return fragment;
}
}
2. 封装 BaseFragment
/**
* Created by Administrator on 2018/4/16/016.
* Bruce Lee
* 备注:Fragment 基类
*/
public abstract class BaseFragment extends LazyLoadFragment {
protected View rootView;
private Intent intent;
//获取fragment布局文件ID
protected abstract int setLayoutId();
//进行初始化的方法
protected abstract void init(View view, Bundle savedInstanceState);
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (rootView == null){
rootView = inflater.inflate(setLayoutId(), container, false);
ButterKnife.bind(this, rootView);
init(rootView, savedInstanceState);
}
return rootView;
}
@Override
public void onDestroyView() {
super.onDestroyView();
((ViewGroup) rootView.getParent()).removeView(rootView);
}
protected void ChangeActivity(Class<?> cls,boolean isFinish){
intent = new Intent(getActivity(),cls);
startActivity(intent);
if (isFinish) getActivity().finish();
}
}
3. 实战使用
/**
* Created by Administrator on 2018/4/16/016.
* Bruce Lee
* 备注:个人中心
*/
public class MineFragment extends BaseFragment {
@Override
protected int setLayoutId() {
return R.layout.fragment_mine_view;
}
@Override
protected void init(View view, Bundle savedInstanceState) {
// 初始化 布局
}
@Override
public void fetchData() {
// 做网络请求
}
}