public abstract class BaseLazyFragment extends Fragment {
protected boolean isVisible;
/**
* to judge if is visible to user
* @param isVisibleToUser
*/
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(getUserVisibleHint()) {
this.isVisible = true;
onVisible();
} else {
this.isVisible = false;
onInvisible();
}
}
/**
* when the fragment is not visible to user
*/
protected void onInvisible() {
Loggy.e("do onInvisible");
}
/**
* when the fragment is visible to user
*
* lazyload
*/
protected void onVisible() {
Loggy.e("do onVisible---");
lazyLoad();
}
protected abstract void lazyLoad();
}
次に、たとえばBaseLazyFragmentを拡張する顧客フラグメントを作成できます
public class NewsFragment extends BaseLazyFragment {
private boolean isPrepared;
//a flag to judge init action has finished
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_news_page,null);
//do init
// when init is finish , set flag true;
isPrepared = true;
lazyLoad();
return view;
}
@Override
protected void lazyLoad() {
// according this judge, can prevent nullpointerexception
if(!isPrepared || !isVisible){
return;
}
// assignment the view
// get data from network assignment to varible
}
}
setUserVisibleHint()
フラグメント作成 setUserVisibleHint() メソッドが最初に onCreateView() よりもヘッダーであるため、oncreateView() が呼び出されないため、lazyLoad() メソッドが NullPointerException をスローする可能性があるため、フラグ変数を作成する必要があります --> isPrepared.
onCreateView()
参照リンク