android Fragment 懒加载布局


     当一个页面包含多个Fragment 时,你希望不可见的Fragment 延迟到可见时再加载,下面介绍一种方法,代码如下

public abstract class LazyLoadFragment extends BaseRequestFragment {
    private FrameLayout mContentView;
    private Bundle mSavedInstanceState;

    private boolean mIsFirstLoad = true;
    @Override
    public final View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mContentView = (FrameLayout)inflater.inflate(R.layout.fragment_base_lazy_load_layout, null);
        mSavedInstanceState = savedInstanceState;
        return mContentView;
    }

    public abstract View onLazyCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState);

    public final void replaceLazyView() {
        FrameLayout contentView = mContentView;
        View lazyCreateView = onLazyCreateView(getActivity().getLayoutInflater(), contentView, mSavedInstanceState);
        if (contentView.indexOfChild(lazyCreateView) < 0) {
            contentView.removeAllViews();
            contentView.addView(lazyCreateView);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && mIsFirstLoad) {
            replaceLazyView();
            mIsFirstLoad = false;
        }
    }
}
   然后需要延迟加载的页面就继承LazyLoadFragment,然后重写onLazyCreateView方法初始化你的布局

你可能感兴趣的:(android)