目錄介紹
- 01.界面狀态有哪些
- 02.采用include方式管理
- 03.在Base類中處理邏輯
- 04.如何降低偶性和入侵性
- 05.封裝低入侵性狀态庫
- 5.1 自定義幀布局
- 5.2 自定義狀态管理器
- 5.3 如何管理多種狀态
- 06.封裝庫極緻優化點說明
- 6.1 用ViewStub顯示布局
- 6.2 處理重新加載邏輯
- 07.如何使用該封裝庫
好消息
- 部落格筆記大彙總【16年3月到至今】,包括Java基礎及深入知識點,Android技術部落格,Python學習筆記等等,還包括平時開發中遇到的bug彙總,當然也在工作之餘收集了大量的面試題,長期更新維護并且修正,持續完善……開源的檔案是markdown格式的!同時也開源了生活部落格,從12年起,積累共計N篇[近100萬字,陸續搬到網上],轉載請注明出處,謝謝!
- 連結位址: https://github.com/yangchong211/YCBlogs
- 如果覺得好,可以star一下,謝謝!當然也歡迎提出建議,萬事起于忽微,量變引起質變!
- 在Android中,不管是activity或者fragment,在加載視圖的時候都有可能會出現多種不同的狀态頁面View。比如常見的就有這些:
- 内容界面,也就是正常有資料頁面
- 加載資料中,加載loading
- 加載資料錯誤,請求資料異常
- 加載後沒有資料,請求資料為空
- 沒有網絡,網絡異常
- 同時,思考一下幾個問題。
- 怎樣切換界面狀态?有些界面想定制自定義狀态?狀态如何添加點選事件?下面就為解決這些問題!
- 為何要這樣?
- 一般在加載網絡資料時,需要使用者等待的場景,顯示一個加載的Loading動畫可以讓使用者知道App正在加載資料,而不是程式卡死,進而給使用者較好的使用體驗。
- 當加載的資料為空時顯示一個資料為空的視圖、在資料加載失敗時顯示加載失敗對應的UI并支援點選重試會比白屏的使用者體驗更好一些。
- 加載中、加載失敗、空資料等不同狀态頁面風格,一般來說在App内的所有頁面中需要保持一緻,也就是需要做到全局統一。
- 直接把這些界面include到main界面中,然後動态去切換界面,具體一點的做法如下所示。
- 在布局中,會存放多個狀态的布局。然後在頁面中根據邏輯将對應的布局給顯示或者隐藏,但存在諸多問題。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/activity_main" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <!--正常時布局--> <include layout="@layout/activity_content"/> <!--加載loading布局--> <include layout="@layout/activity_loading"/> <!--異常時布局--> <include layout="@layout/activity_error"/> <!--空資料時布局--> <include layout="@layout/activity_emptydata"/> </LinearLayout>
- 存在的問題分析
- 後來發現這樣處理不容易複用到其他項目中,代碼複用性很低
- 在activity中處理這些狀态的顯示和隐藏比較亂
- 調用setContentView方法時,是将所有的布局給加載繪制出來。其實沒有必要
- 如果将邏輯寫在BaseActivity中,利用子類繼承父類特性,在父類中寫切換狀态,但有些界面如果沒有繼承父類,又該如何處理
- 首先是定義一個自定義的控件,比如把它命名成LoadingView,然後在這個裡面include一個布局,該布局包含一些不同狀态的視圖。代碼思路如下所示:
public class LoadingView extends LinearLayout implements View.OnClickListener { public static final int LOADING = 0; public static final int STOP_LOADING = 1; public static final int NO_DATA = 2; public static final int NO_NETWORK = 3; public static final int GONE = 4; public static final int LOADING_DIALOG = 5; private TextView mNoDataTextView; private ProgressBar mLoadingProgressBar; private RelativeLayout mRlError; private LinearLayout mLlLoading; private View mView; private OnRefreshListener mListener; public void setRefrechListener(OnRefreshListener mListener) { this.mListener = mListener; } public interface OnRefreshListener { void refresh(); } public LoadingView(Context context) { super(context); init(context); } public LoadingView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public LoadingView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mView = inflater.inflate(R.layout.common_loading_get, this); mLoadingProgressBar = (ProgressBar) mView.findViewById(R.id.mLoadingProgressBar); mNoDataTextView = (TextView) mView.findViewById(R.id.mNoDataTextView); mLlLoading = (LinearLayout) mView.findViewById(R.id.ll_loading); mRlError = (RelativeLayout) mView.findViewById(R.id.rl_error); mRlError.setOnClickListener(this); setStatue(GONE); } public void setStatue(int status) { setVisibility(View.VISIBLE); try { if (status == LOADING) {//更新 mRlError.setVisibility(View.GONE); mLlLoading.setVisibility(View.VISIBLE); } else if (status == STOP_LOADING) { setVisibility(View.GONE); } else if (status == NO_DATA) {//無資料情況 mRlError.setVisibility(View.VISIBLE); mLlLoading.setVisibility(View.GONE); mNoDataTextView.setText("暫無資料"); } else if (status == NO_NETWORK) {//無網絡情況 mRlError.setVisibility(View.VISIBLE); mLlLoading.setVisibility(View.GONE); mNoDataTextView.setText("網絡加載失敗,點選重新加載"); } else { setVisibility(View.GONE); } } catch (OutOfMemoryError e) { } } @Override public void onClick(View v) { mListener.refresh(); setStatue(LOADING); } }
- 然後在BaseActivity/BaseFragment中封裝LoadingView的初始化邏輯,并封裝加載狀态切換時的UI顯示邏輯,暴露給子類以下方法:
void showLoading(); //調用此方法顯示加載中的動畫 void showLoadFailed(); //調用此方法顯示加載失敗界面 void showEmpty(); //調用此方法顯示空頁面 void onClickRetry(); //子類中實作,點選重試的回調方法
- 在BaseActivity/BaseFragment的子類中可通過上一步的封裝比較友善地使用加載狀态顯示功能。這種使用方式耦合度太高,每個頁面的布局檔案中都需要添加LoadingView,使用起來不友善而且維護成本較高,比如說有時候異常狀态的布局各個頁面不同,那麼難以自定義處理,修改起來成本較高。
- 同時如果是要用這種狀态管理工具,則需要在需要的頁面布局中添加該LoadingView視圖。這樣也能夠完成需求,但是感覺有點麻煩。
- 具體如何使用它進行狀态管理呢?可以看到在對應的布局中需要寫上LoadingView
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <com.cheoo.app.view.recyclerview.TypeRecyclerView android:id="@+id/mRecyclerView" android:layout_width="match_parent" android:layout_height="match_parent" android:overScrollMode="never" android:scrollbars="none"> </com.cheoo.app.view.recyclerview.TypeRecyclerView> <com.cheoo.app.view.LoadingView android:id="@+id/mLoadingView" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
- 那麼,如果某個子類不想繼承BaseActivity類,如何使用該狀态管理器呢?代碼中可以這種使用。
mLoadingView = (LoadingView)findViewById(R.id.mLoadingView); mLoadingView.setStatue(LoadingView.LOADING); mLoadingView.setStatue(LoadingView.STOP_LOADING); mLoadingView.setStatue(LoadingView.NO_NETWORK); mLoadingView.setStatue(LoadingView.NO_DATA);
-
讓View狀态的切換和Activity徹底分離開,必須把這些狀态View都封裝到一個管理類中,然後暴露出幾個方法來實作View之間的切換。
在不同的項目中可以需要的View也不一樣,是以考慮把管理類設計成builder模式來自由的添加需要的狀态View。
- 那麼如何降低耦合性,讓代碼入侵性低。友善維護和修改,且移植性強呢?大概具備這樣的條件……
- 可以運用在activity或者fragment中
- 不需要在布局中添加LoadingView,而是統一管理不同狀态視圖,同時暴露對外設定自定義狀态視圖方法,友善UI特定頁面定制
- 支援設定自定義不同狀态視圖,即使在BaseActivity統一處理狀态視圖管理,也支援單個頁面定制
- 在加載視圖的時候像異常和空頁面能否用ViewStub代替,這樣減少繪制,隻有等到出現異常和空頁面時,才将視圖給inflate出來
- 當頁面出現網絡異常頁面,空頁面等,頁面會有互動事件,這時候可以設定點選設定網絡或者點選重新加載等等
- 首先需要自定義一個狀态StateFrameLayout布局,它是繼承FrameLayout。在這個類中,目前是設定五種不同狀态的視圖布局,主要的功能操作是顯示或者隐藏布局。為了後期代碼維護性,根據面向對象的思想,類盡量保證單一職責,是以關于狀态切換,以及設定自定義狀态布局,把這個功能分離處理,放到一個StateLayoutManager中處理。
- 看代碼可知,這個類的功能非常明确,就是隐藏或者展示視圖作用。
/** * <pre> * @author yangchong * blog : https://github.com/yangchong211/YCStateLayout * time : 2017/7/6 * desc : 自定義幀布局 * revise: * </pre> */ public class StateFrameLayout extends FrameLayout { /** * loading 加載id */ public static final int LAYOUT_LOADING_ID = 1; /** * 内容id */ public static final int LAYOUT_CONTENT_ID = 2; /** * 異常id */ public static final int LAYOUT_ERROR_ID = 3; /** * 網絡異常id */ public static final int LAYOUT_NETWORK_ERROR_ID = 4; /** * 空資料id */ public static final int LAYOUT_EMPTY_DATA_ID = 5; /** * 存放布局集合 */ private SparseArray<View> layoutSparseArray = new SparseArray<>(); //private HashMap<Integer,View> map = new HashMap<>(); /** * 布局管理器 */ private StateLayoutManager mStatusLayoutManager; public StateFrameLayout(Context context) { super(context); } public StateFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); } public StateFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setStatusLayoutManager(StateLayoutManager statusLayoutManager) { mStatusLayoutManager = statusLayoutManager; //添加所有的布局到幀布局 addAllLayoutToRootLayout(); } private void addAllLayoutToRootLayout() { if (mStatusLayoutManager.contentLayoutResId != 0) { addLayoutResId(mStatusLayoutManager.contentLayoutResId, StateFrameLayout.LAYOUT_CONTENT_ID); } if (mStatusLayoutManager.loadingLayoutResId != 0) { addLayoutResId(mStatusLayoutManager.loadingLayoutResId, StateFrameLayout.LAYOUT_LOADING_ID); } if (mStatusLayoutManager.emptyDataVs != null) { addView(mStatusLayoutManager.emptyDataVs); } if (mStatusLayoutManager.errorVs != null) { addView(mStatusLayoutManager.errorVs); } if (mStatusLayoutManager.netWorkErrorVs != null) { addView(mStatusLayoutManager.netWorkErrorVs); } } private void addLayoutResId(@LayoutRes int layoutResId, int id) { View resView = LayoutInflater.from(mStatusLayoutManager.context).inflate(layoutResId, null); layoutSparseArray.put(id, resView); addView(resView); } /** * 顯示loading */ public void showLoading() { if (layoutSparseArray.get(LAYOUT_LOADING_ID) != null) { showHideViewById(LAYOUT_LOADING_ID); } } /** * 顯示内容 */ public void showContent() { if (layoutSparseArray.get(LAYOUT_CONTENT_ID) != null) { showHideViewById(LAYOUT_CONTENT_ID); } } /** * 顯示空資料 */ public void showEmptyData(int iconImage, String textTip) { if (inflateLayout(LAYOUT_EMPTY_DATA_ID)) { showHideViewById(LAYOUT_EMPTY_DATA_ID); emptyDataViewAddData(iconImage, textTip); } } /** * 根據ID顯示隐藏布局 * @param id id值 */ private void showHideViewById(int id) { for (int i = 0; i < layoutSparseArray.size(); i++) { int key = layoutSparseArray.keyAt(i); View valueView = layoutSparseArray.valueAt(i); //顯示該view if(key == id) { valueView.setVisibility(View.VISIBLE); if(mStatusLayoutManager.onShowHideViewListener != null) { mStatusLayoutManager.onShowHideViewListener.onShowView(valueView, key); } } else { if(valueView.getVisibility() != View.GONE) { valueView.setVisibility(View.GONE); if(mStatusLayoutManager.onShowHideViewListener != null) { mStatusLayoutManager.onShowHideViewListener.onHideView(valueView, key); } } } } } /** * 這個是處理ViewStub的邏輯,主要有網絡異常布局,加載異常布局,空資料布局 * @param id 布局id * @return 布爾值 */ private boolean inflateLayout(int id) { boolean isShow = true; //如果為null,則直接傳回false if (layoutSparseArray.get(id) == null) { return false; } switch (id) { case LAYOUT_NETWORK_ERROR_ID: if (mStatusLayoutManager.netWorkErrorVs != null) { View view = mStatusLayoutManager.netWorkErrorVs.inflate(); retryLoad(view, mStatusLayoutManager.netWorkErrorRetryViewId); layoutSparseArray.put(id, view); isShow = true; } else { isShow = false; } break; case LAYOUT_ERROR_ID: if (mStatusLayoutManager.errorVs != null) { View view = mStatusLayoutManager.errorVs.inflate(); if (mStatusLayoutManager.errorLayout != null) { mStatusLayoutManager.errorLayout.setView(view); } retryLoad(view, mStatusLayoutManager.errorRetryViewId); layoutSparseArray.put(id, view); isShow = true; } else { isShow = false; } break; case LAYOUT_EMPTY_DATA_ID: if (mStatusLayoutManager.emptyDataVs != null) { View view = mStatusLayoutManager.emptyDataVs.inflate(); if (mStatusLayoutManager.emptyDataLayout != null) { mStatusLayoutManager.emptyDataLayout.setView(view); } retryLoad(view, mStatusLayoutManager.emptyDataRetryViewId); layoutSparseArray.put(id, view); isShow = true; } else { isShow = false; } break; default: break; } return isShow; } }
- 上面狀态的自定義布局建立出來了,而且隐藏和展示都做了。那麼如何控制設定自定義視圖布局,還有如何控制不同布局之間切換,那麼就需要用到這個類呢! https://github.com/yangchong211/YCStateLayout
- loadingLayoutResId和contentLayoutResId代表等待加載和顯示内容的xml檔案
- 幾種異常狀态要用ViewStub,因為在界面狀态切換中loading和内容View都是一直需要加載顯示的,但是其他的3個隻有在沒資料或者網絡異常的情況下才會加載顯示,是以用ViewStub來加載他們可以提高性能。
- 采用builder模式,十分簡單,代碼如下所示。建立StateFrameLayout對象,然後再設定setStatusLayoutManager,這一步操作是傳遞一個Manager對象到StateFrameLayout,建立連接配接。
public final class StateLayoutManager { final Context context; final int netWorkErrorRetryViewId; final int emptyDataRetryViewId; final int errorRetryViewId; final int loadingLayoutResId; final int contentLayoutResId; final int retryViewId; final int emptyDataIconImageId; final int emptyDataTextTipId; final int errorIconImageId; final int errorTextTipId; final ViewStub emptyDataVs; final ViewStub netWorkErrorVs; final ViewStub errorVs; final AbsViewStubLayout errorLayout; final AbsViewStubLayout emptyDataLayout; private final StateFrameLayout rootFrameLayout; final OnShowHideViewListener onShowHideViewListener; final OnRetryListener onRetryListener; public static Builder newBuilder(Context context) { return new Builder(context); } private StateLayoutManager(Builder builder) { this.context = builder.context; this.loadingLayoutResId = builder.loadingLayoutResId; this.netWorkErrorVs = builder.netWorkErrorVs; this.netWorkErrorRetryViewId = builder.netWorkErrorRetryViewId; this.emptyDataVs = builder.emptyDataVs; this.emptyDataRetryViewId = builder.emptyDataRetryViewId; this.errorVs = builder.errorVs; this.errorRetryViewId = builder.errorRetryViewId; this.contentLayoutResId = builder.contentLayoutResId; this.onShowHideViewListener = builder.onShowHideViewListener; this.retryViewId = builder.retryViewId; this.onRetryListener = builder.onRetryListener; this.emptyDataIconImageId = builder.emptyDataIconImageId; this.emptyDataTextTipId = builder.emptyDataTextTipId; this.errorIconImageId = builder.errorIconImageId; this.errorTextTipId = builder.errorTextTipId; this.errorLayout = builder.errorLayout; this.emptyDataLayout = builder.emptyDataLayout; //建立幀布局 rootFrameLayout = new StateFrameLayout(this.context); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); rootFrameLayout.setLayoutParams(layoutParams); //設定狀态管理器 rootFrameLayout.setStatusLayoutManager(this); } /** * 顯示loading */ public void showLoading() { rootFrameLayout.showLoading(); } /** * 顯示内容 */ public void showContent() { rootFrameLayout.showContent(); } /** * 顯示空資料 */ public void showEmptyData(int iconImage, String textTip) { rootFrameLayout.showEmptyData(iconImage, textTip); } /** * 顯示空資料 */ public void showEmptyData() { showEmptyData(0, ""); } /** * 顯示空資料 */ public void showLayoutEmptyData(Object... objects) { rootFrameLayout.showLayoutEmptyData(objects); } /** * 顯示網絡異常 */ public void showNetWorkError() { rootFrameLayout.showNetWorkError(); } /** * 顯示異常 */ public void showError(int iconImage, String textTip) { rootFrameLayout.showError(iconImage, textTip); } /** * 顯示異常 */ public void showError() { showError(0, ""); } public void showLayoutError(Object... objects) { rootFrameLayout.showLayoutError(objects); } /** * 得到root 布局 */ public View getRootLayout() { return rootFrameLayout; } public static final class Builder { private Context context; private int loadingLayoutResId; private int contentLayoutResId; private ViewStub netWorkErrorVs; private int netWorkErrorRetryViewId; private ViewStub emptyDataVs; private int emptyDataRetryViewId; private ViewStub errorVs; private int errorRetryViewId; private int retryViewId; private int emptyDataIconImageId; private int emptyDataTextTipId; private int errorIconImageId; private int errorTextTipId; private AbsViewStubLayout errorLayout; private AbsViewStubLayout emptyDataLayout; private OnShowHideViewListener onShowHideViewListener; private OnRetryListener onRetryListener; Builder(Context context) { this.context = context; } /** * 自定義加載布局 */ public Builder loadingView(@LayoutRes int loadingLayoutResId) { this.loadingLayoutResId = loadingLayoutResId; return this; } /** * 自定義網絡錯誤布局 */ public Builder netWorkErrorView(@LayoutRes int newWorkErrorId) { netWorkErrorVs = new ViewStub(context); netWorkErrorVs.setLayoutResource(newWorkErrorId); return this; } /** * 自定義加載空資料布局 */ public Builder emptyDataView(@LayoutRes int noDataViewId) { emptyDataVs = new ViewStub(context); emptyDataVs.setLayoutResource(noDataViewId); return this; } /** * 自定義加載錯誤布局 */ public Builder errorView(@LayoutRes int errorViewId) { errorVs = new ViewStub(context); errorVs.setLayoutResource(errorViewId); return this; } /** * 自定義加載内容正常布局 */ public Builder contentView(@LayoutRes int contentLayoutResId) { this.contentLayoutResId = contentLayoutResId; return this; } public Builder errorLayout(AbsViewStubLayout errorLayout) { this.errorLayout = errorLayout; this.errorVs = errorLayout.getLayoutVs(); return this; } public Builder emptyDataLayout(AbsViewStubLayout emptyDataLayout) { this.emptyDataLayout = emptyDataLayout; this.emptyDataVs = emptyDataLayout.getLayoutVs(); return this; } public Builder netWorkErrorRetryViewId(@LayoutRes int netWorkErrorRetryViewId) { this.netWorkErrorRetryViewId = netWorkErrorRetryViewId; return this; } public Builder emptyDataRetryViewId(@LayoutRes int emptyDataRetryViewId) { this.emptyDataRetryViewId = emptyDataRetryViewId; return this; } public Builder errorRetryViewId(@LayoutRes int errorRetryViewId) { this.errorRetryViewId = errorRetryViewId; return this; } public Builder retryViewId(@LayoutRes int retryViewId) { this.retryViewId = retryViewId; return this; } public Builder emptyDataIconImageId(@LayoutRes int emptyDataIconImageId) { this.emptyDataIconImageId = emptyDataIconImageId; return this; } public Builder emptyDataTextTipId(@LayoutRes int emptyDataTextTipId) { this.emptyDataTextTipId = emptyDataTextTipId; return this; } public Builder errorIconImageId(@LayoutRes int errorIconImageId) { this.errorIconImageId = errorIconImageId; return this; } public Builder errorTextTipId(@LayoutRes int errorTextTipId) { this.errorTextTipId = errorTextTipId; return this; } /** * 為狀态View顯示隐藏監聽事件 * @param listener listener * @return */ public Builder onShowHideViewListener(OnShowHideViewListener listener) { this.onShowHideViewListener = listener; return this; } /** * 為重試加載按鈕的監聽事件 * @param onRetryListener listener * @return */ public Builder onRetryListener(OnRetryListener onRetryListener) { this.onRetryListener = onRetryListener; return this; } /** * 建立對象 * @return */ public StateLayoutManager build() { return new StateLayoutManager(this); } } }
- 大約5種狀态,如何管理這些狀态?添加到集合中,Android中選用SparseArray比HashMap更省記憶體,在某些條件下性能更好,主要是因為它避免了對key的自動裝箱(int轉為Integer類型),它内部則是通過兩個數組來進行資料存儲的,一個存儲key,另外一個存儲value,為了優化性能,它内部對資料還采取了壓縮的方式來表示稀疏數組的資料,進而節約記憶體空間
/**存放布局集合 */ private SparseArray<View> layoutSparseArray = new SparseArray(); /**将布局添加到集合 */ private void addLayoutResId(@LayoutRes int layoutResId, int id) { View resView = LayoutInflater.from(mStatusLayoutManager.context).inflate(layoutResId, null); layoutSparseArray.put(id, resView); addView(resView); } //那麼哪裡從集合中取資料呢 public void showContent() { if (layoutSparseArray.get(LAYOUT_CONTENT_ID) != null) { showHideViewById(LAYOUT_CONTENT_ID); } }
- 方法裡面通過id判斷來執行不同的代碼,首先判斷ViewStub是否為空,如果為空就代表沒有添加這個View就傳回false,不為空就加載View并且添加到集合當中,然後調用showHideViewById方法顯示隐藏View,retryLoad方法是給重試按鈕添加事件
- 注意,即使當你設定了多種不同狀态視圖,調用setContentView的時候,因為異常頁面使用ViewStub,是以在繪制的時候不會影響性能的。
/** * 顯示loading */ public void showLoading() { if (layoutSparseArray.get(LAYOUT_LOADING_ID) != null) showHideViewById(LAYOUT_LOADING_ID); } /** * 顯示内容 */ public void showContent() { if (layoutSparseArray.get(LAYOUT_CONTENT_ID) != null) showHideViewById(LAYOUT_CONTENT_ID); } //調用inflateLayout方法,方法傳回true然後調用showHideViewById方法 private boolean inflateLayout(int id) { boolean isShow = true; if (layoutSparseArray.get(id) != null) return isShow; switch (id) { case LAYOUT_NETWORK_ERROR_ID: if (mStatusLayoutManager.netWorkErrorVs != null) { View view = mStatusLayoutManager.netWorkErrorVs.inflate(); retryLoad(view, mStatusLayoutManager.netWorkErrorRetryViewId); layoutSparseArray.put(id, view); isShow = true; } else { isShow = false; } break; case LAYOUT_ERROR_ID: if (mStatusLayoutManager.errorVs != null) { View view = mStatusLayoutManager.errorVs.inflate(); if (mStatusLayoutManager.errorLayout != null) mStatusLayoutManager.errorLayout.setView(view); retryLoad(view, mStatusLayoutManager.errorRetryViewId); layoutSparseArray.put(id, view); isShow = true; } else { isShow = false; } break; case LAYOUT_EMPTYDATA_ID: if (mStatusLayoutManager.emptyDataVs != null) { View view = mStatusLayoutManager.emptyDataVs.inflate(); if (mStatusLayoutManager.emptyDataLayout != null) mStatusLayoutManager.emptyDataLayout.setView(view); retryLoad(view, mStatusLayoutManager.emptyDataRetryViewId); layoutSparseArray.put(id, view); isShow = true; } else { isShow = false; } break; } return isShow; }
- 最後看看重新加載方法
/** * 重試加載 */ private void retryLoad(View view, int id) { View retryView = view.findViewById(mStatusLayoutManager.retryViewId != 0 ? mStatusLayoutManager.retryViewId : id); if (retryView == null || mStatusLayoutManager.onRetryListener == null) return; retryView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mStatusLayoutManager.onRetryListener.onRetry(); } }); }
- 可以自由切換内容,空資料,異常錯誤,加載,網絡錯誤等5種狀态。父類BaseActivity直接暴露5中狀态,友善子類統一管理狀态切換,這裡fragment的封裝和activity差不多。
/** * ================================================ * 作 者:楊充 * 版 本:1.0 * 建立日期:2017/7/6 * 描 述:抽取類 * 修訂曆史: * ================================================ */ public abstract class BaseActivity extends AppCompatActivity { protected StatusLayoutManager statusLayoutManager; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_base_view); initStatusLayout(); initBaseView(); initToolBar(); initView(); } //子類必須重寫該方法 protected abstract void initStatusLayout(); protected abstract void initView(); /** * 擷取到布局 */ private void initBaseView() { LinearLayout ll_main = (LinearLayout) findViewById(R.id.ll_main); ll_main.addView(statusLayoutManager.getRootLayout()); } //正常展示資料狀态 protected void showContent() { statusLayoutManager.showContent(); } //加載資料為空時狀态 protected void showEmptyData() { statusLayoutManager.showEmptyData(); } //加載資料錯誤時狀态 protected void showError() { statusLayoutManager.showError(); } //網絡錯誤時狀态 protected void showNetWorkError() { statusLayoutManager.showNetWorkError(); } //正在加載中狀态 protected void showLoading() { statusLayoutManager.showLoading(); } }
- 子類繼承BaseActivity後,該如何操作呢?具體如下所示
@Override protected void initStatusLayout() { statusLayoutManager = StateLayoutManager.newBuilder(this) .contentView(R.layout.activity_main) .emptyDataView(R.layout.activity_emptydata) .errorView(R.layout.activity_error) .loadingView(R.layout.activity_loading) .netWorkErrorView(R.layout.activity_networkerror) .build(); } //或者添加上監聽事件 @Override protected void initStatusLayout() { statusLayoutManager = StateLayoutManager.newBuilder(this) .contentView(R.layout.activity_content_data) .emptyDataView(R.layout.activity_empty_data) .errorView(R.layout.activity_error_data) .loadingView(R.layout.activity_loading_data) .netWorkErrorView(R.layout.activity_networkerror) .onRetryListener(new OnRetryListener() { @Override public void onRetry() { //為重試加載按鈕的監聽事件 } }) .onShowHideViewListener(new OnShowHideViewListener() { @Override public void onShowView(View view, int id) { //為狀态View顯示監聽事件 } @Override public void onHideView(View view, int id) { //為狀态View隐藏監聽事件 } }) .build(); } //如何切換狀态呢? showContent(); showEmptyData(); showError(); showLoading(); showNetWorkError(); //或者這樣操作也可以 statusLayoutManager.showLoading(); statusLayoutManager.showContent();
- 那麼如何設定狀态頁面的互動事件呢?當狀态是加載資料失敗時,點選可以重新整理資料;當狀态是無網絡時,點選可以設定網絡。代碼如下所示:
/** * 點選重新重新整理 */ private void initErrorDataView() { statusLayoutManager.showError(); LinearLayout ll_error_data = (LinearLayout) findViewById(R.id.ll_error_data); ll_error_data.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { initData(); adapter.notifyDataSetChanged(); showContent(); } }); } /** * 點選設定網絡 */ private void initSettingNetwork() { statusLayoutManager.showNetWorkError(); LinearLayout ll_set_network = (LinearLayout) findViewById(R.id.ll_set_network); ll_set_network.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent("android.settings.WIRELESS_SETTINGS"); startActivity(intent); } }); }
- 那有些頁面想要自定義指定的狀态頁面UI,又該如何操作呢?倘若有些頁面想定制狀态布局,也可以自由實作,很簡單:
/** * 自定義加載資料為空時的狀态布局 */ private void initEmptyDataView() { statusLayoutManager.showEmptyData(); //此處是自己定義的狀态布局 statusLayoutManager.showLayoutEmptyData(R.layout.activity_emptydata); LinearLayout ll_empty_data = (LinearLayout) findViewById(R.id.ll_empty_data); ll_empty_data.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { initData(); adapter.notifyDataSetChanged(); showContent(); } }); }
其他介紹
01.關于部落格彙總連結
02.關于我的部落格
- github: https://github.com/yangchong211
- 知乎: https://www.zhihu.com/people/yczbj/activities
- 簡書: http://www.jianshu.com/u/b7b2c6ed9284
- csdn: http://my.csdn.net/m0_37700275
- 喜馬拉雅聽書: http://www.ximalaya.com/zhubo/71989305/
- 開源中國: https://my.oschina.net/zbj1618/blog
- 泡在網上的日子: http://www.jcodecraeer.com/member/content_list.php?channelid=1
- 郵箱:[email protected]
- 阿裡雲部落格: https://yq.aliyun.com/users/article?spm=5176.100- 239.headeruserinfo.3.dT4bcV
- segmentfault頭條: https://segmentfault.com/u/xiangjianyu/articles
- 掘金: https://juejin.im/user/5939433efe88c2006afa0c6e