public class LazyFragment extends Fragment {
private View mRootView;
private boolean mIsInited;
private boolean mIsPrepared;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_lazy, container, false);
mIsPrepared = true;
lazyLoad();
return mRootView;
}
public void lazyLoad() {
if (getUserVisibleHint() && mIsPrepared && !mIsInited) {
//異步初始化廊勃,在初始化后顯示正常UI
loadData();
}
}
private void loadData() {
new Thread() {
public void run() {
//1. 加載數(shù)據(jù)
//2. 更新UI
//3. mIsInited = true
}
}.start();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
lazyLoad();
}
}
public static LazyFragment newInstance() {
return new LazyFragment();
}
}
注意點:
在Fragment中有兩個變量控制是否需要做數(shù)據(jù)加載:
mIsPrepared:表示UI是否準(zhǔn)備好,因為數(shù)據(jù)加載后需要更新UI演顾,如果UI還沒有inflate供搀,就不需要做數(shù)據(jù)加載隅居,因為setUserVisibleHint()會在onCreateView()之前調(diào)用一次钠至,如果此時調(diào)用,UI還沒有inflate胎源,因此不能加載數(shù)據(jù)棉钧。
mIsInited:表示是否已經(jīng)做過數(shù)據(jù)加載,如果做過了就不需要做了涕蚤。因為setUserVisibleHint(true)在界面可見時都會調(diào)用宪卿,如果滑到該界面做過數(shù)據(jù)加載后的诵,滑走,再滑回來佑钾,還是會調(diào)用setUserVisibleHint(true)西疤,此時由于mIsInited=true,因此不會再做一遍數(shù)據(jù)加載休溶。
lazyLoad():懶加載的核心類代赁,在該方法中,只有界面可見(getUserVisibleHint()==true)兽掰、UI準(zhǔn)備好(mIsPrepared==true)芭碍、過去沒做過數(shù)據(jù)加載(mIsInited==false)時,才需要調(diào)loadData()做數(shù)據(jù)加載孽尽,數(shù)據(jù)加載做完后把mIsInited置為true窖壕。
布局XML主要分兩個container,一個是初始顯示的狀態(tài)杉女,即R.id.container_empty瞻讽,當(dāng)數(shù)據(jù)加載完成,就顯示R.id.container:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/container_empty"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="正在加載"
/>
</RelativeLayout>
<RelativeLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
>
...
</RelativeLayout>
</FrameLayout>
《Android基礎(chǔ):Fragment宠纯,看這篇就夠了》
https://mp.weixin.qq.com/s?__biz=MzA3NTYzODYzMg==&mid=2653579375&idx=1&sn=4f80a50961329e19cad6cd0e1bff20d9&chksm=84b3ba68b3c4337e28a870d6338fa3035d299a2aff2f3bf3f82304417aa7a83deab0b95031e6&mpshare=1&scene=24&srcid=1109JSBYaqYQZDGpV9sLDjIQ#rd