Last active
June 11, 2018 05:32
-
-
Save lzh77/1414bbd7ba6391d420946ac7a5b7b0c0 to your computer and use it in GitHub Desktop.
懒加载fragment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class LazyFragment extends BaseFragment { | |
private boolean isPrepared; | |
private boolean isFirstResume = true; | |
private boolean isFirstVisible = true; | |
private boolean isFirstInvisible = true; | |
@Override | |
public void onActivityCreated(@Nullable Bundle savedInstanceState) { | |
super.onActivityCreated(savedInstanceState); | |
initPrepare(); | |
} | |
@Override | |
public void onResume() { | |
super.onResume(); | |
if (isFirstResume) { | |
isFirstResume = false; | |
return; | |
} | |
if (getUserVisibleHint()) { | |
onInvisible(); | |
} | |
} | |
@Override | |
public void onPause() { | |
super.onPause(); | |
if (getUserVisibleHint()) { | |
onInvisible(); | |
} | |
} | |
@Override | |
public void setUserVisibleHint(boolean isVisibleToUser) { | |
super.setUserVisibleHint(isVisibleToUser); | |
if (isVisibleToUser) { | |
if (isFirstVisible) { | |
isFirstVisible = false; | |
initPrepare(); | |
} else { | |
onVisible(); | |
} | |
} else { | |
if (isFirstInvisible) { | |
isFirstInvisible = false; | |
onFirstInvisible(); | |
} else { | |
onInvisible(); | |
} | |
} | |
} | |
public synchronized void initPrepare() { | |
if (isPrepared) { | |
onFirstVisible(); | |
} else { | |
isPrepared = true; | |
} | |
} | |
protected abstract void onFirstVisible(); | |
protected abstract void onFirstInvisible(); | |
protected abstract void onVisible(); | |
protected abstract void onInvisible(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment