Skip to content

Instantly share code, notes, and snippets.

@tysheng
Created November 17, 2016 13:48
Show Gist options
  • Save tysheng/e5f7062e43db73282dec8eb059317ce9 to your computer and use it in GitHub Desktop.
Save tysheng/e5f7062e43db73282dec8eb059317ce9 to your computer and use it in GitHub Desktop.
A fragment can be lazy.
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import butterknife.ButterKnife;
import butterknife.Unbinder;
/**
* A fragment can be lazy.
* Created by tysheng
* Date: 2016/11/17 21:35.
* Email: tyshengsx@gmail.com
*/
public abstract class LazyFrament extends Fragment {
protected View mRootView;
protected Context mContext;
private Unbinder mBinder;
/**
* flag isLazyInitialized
*/
private boolean isLazyInitialized;
/**
* flag isViewCreated
*/
private boolean isViewCreated;
private boolean isLazyMode;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getContext();
setLazyMode(true);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(getLayoutId(), container, false);
mBinder = ButterKnife.bind(this, mRootView);
initView();
return mRootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (!isLazyMode) initData();
isViewCreated = true;
}
@Override
public void onDestroyView() {
super.onDestroyView();
mBinder.unbind();
isLazyInitialized = false;
isViewCreated = false;
}
/**
* whether to open lazy mode.
* <p>
* set it in initView() or before
*
* @param lazyMode
*/
public void setLazyMode(boolean lazyMode) {
isLazyMode = lazyMode;
}
/**
* Key method to lazy init data
*/
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getUserVisibleHint() && !isLazyInitialized && isViewCreated && isLazyMode) {
isLazyInitialized = true;
initData();
}
}
protected abstract void initView();
protected abstract void initData();
protected abstract int getLayoutId();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment