Android中不同狀態(tài)頁(yè)面管理優(yōu)化技巧詳解
01.界面狀態(tài)有哪些
在Android中,不管是activity或者fragment,在加載視圖的時(shí)候都有可能會(huì)出現(xiàn)多種不同的狀態(tài)頁(yè)面View。比如常見(jiàn)的就有這些:
- 內(nèi)容界面,也就是正常有數(shù)據(jù)頁(yè)面
- 加載數(shù)據(jù)中,加載loading
- 加載數(shù)據(jù)錯(cuò)誤,請(qǐng)求數(shù)據(jù)異常
- 加載后沒(méi)有數(shù)據(jù),請(qǐng)求數(shù)據(jù)為空
- 沒(méi)有網(wǎng)絡(luò),網(wǎng)絡(luò)異常
同時(shí),思考一下幾個(gè)問(wèn)題。
怎樣切換界面狀態(tài)?有些界面想定制自定義狀態(tài)?狀態(tài)如何添加點(diǎn)擊事件?下面就為解決這些問(wèn)題!
為何要這樣?
- 一般在加載網(wǎng)絡(luò)數(shù)據(jù)時(shí),需要用戶等待的場(chǎng)景,顯示一個(gè)加載的Loading動(dòng)畫(huà)可以讓用戶知道App正在加載數(shù)據(jù),而不是程序卡死,從而給用戶較好的使用體驗(yàn)。
- 當(dāng)加載的數(shù)據(jù)為空時(shí)顯示一個(gè)數(shù)據(jù)為空的視圖、在數(shù)據(jù)加載失敗時(shí)顯示加載失敗對(duì)應(yīng)的UI并支持點(diǎn)擊重試會(huì)比白屏的用戶體驗(yàn)更好一些。
- 加載中、加載失敗、空數(shù)據(jù)等不同狀態(tài)頁(yè)面風(fēng)格,一般來(lái)說(shuō)在App內(nèi)的所有頁(yè)面中需要保持一致,也就是需要做到全局統(tǒng)一。
02.采用include方式管理
直接把這些界面include到main界面中,然后動(dòng)態(tài)去切換界面,具體一點(diǎn)的做法如下所示。
在布局中,會(huì)存放多個(gè)狀態(tài)的布局。然后在頁(yè)面中根據(jù)邏輯將對(duì)應(yīng)的布局給顯示或者隱藏,但存在諸多問(wèn)題。
<?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">
<!--正常時(shí)布局-->
<include layout="@layout/activity_content"/>
<!--加載loading布局-->
<include layout="@layout/activity_loading"/>
<!--異常時(shí)布局-->
<include layout="@layout/activity_error"/>
<!--空數(shù)據(jù)時(shí)布局-->
<include layout="@layout/activity_emptydata"/>
</LinearLayout>
存在的問(wèn)題分析
- 后來(lái)發(fā)現(xiàn)這樣處理不容易復(fù)用到其他項(xiàng)目中,代碼復(fù)用性很低
- 在activity中處理這些狀態(tài)的顯示和隱藏比較亂
- 調(diào)用setContentView方法時(shí),是將所有的布局給加載繪制出來(lái)。其實(shí)沒(méi)有必要
- 如果將邏輯寫(xiě)在BaseActivity中,利用子類繼承父類特性,在父類中寫(xiě)切換狀態(tài),但有些界面如果沒(méi)有繼承父類,又該如何處理
03.在Base類中處理邏輯
首先是定義一個(gè)自定義的控件,比如把它命名成LoadingView,然后在這個(gè)里面include一個(gè)布局,該布局包含一些不同狀態(tài)的視圖。代碼思路如下所示:
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) {//無(wú)數(shù)據(jù)情況
mRlError.setVisibility(View.VISIBLE);
mLlLoading.setVisibility(View.GONE);
mNoDataTextView.setText("暫無(wú)數(shù)據(jù)");
} else if (status == NO_NETWORK) {//無(wú)網(wǎng)絡(luò)情況
mRlError.setVisibility(View.VISIBLE);
mLlLoading.setVisibility(View.GONE);
mNoDataTextView.setText("網(wǎng)絡(luò)加載失敗,點(diǎn)擊重新加載");
} else {
setVisibility(View.GONE);
}
} catch (OutOfMemoryError e) {
}
}
@Override
public void onClick(View v) {
mListener.refresh();
setStatue(LOADING);
}
}
然后在BaseActivity/BaseFragment中封裝LoadingView的初始化邏輯,并封裝加載狀態(tài)切換時(shí)的UI顯示邏輯,暴露給子類以下方法:
void showLoading(); //調(diào)用此方法顯示加載中的動(dòng)畫(huà) void showLoadFailed(); //調(diào)用此方法顯示加載失敗界面 void showEmpty(); //調(diào)用此方法顯示空頁(yè)面 void onClickRetry(); //子類中實(shí)現(xiàn),點(diǎn)擊重試的回調(diào)方法
在BaseActivity/BaseFragment的子類中可通過(guò)上一步的封裝比較方便地使用加載狀態(tài)顯示功能。這種使用方式耦合度太高,每個(gè)頁(yè)面的布局文件中都需要添加LoadingView,使用起來(lái)不方便而且維護(hù)成本較高,比如說(shuō)有時(shí)候異常狀態(tài)的布局各個(gè)頁(yè)面不同,那么難以自定義處理,修改起來(lái)成本較高。
同時(shí)如果是要用這種狀態(tài)管理工具,則需要在需要的頁(yè)面布局中添加該LoadingView視圖。這樣也能夠完成需求,但是感覺(jué)有點(diǎn)麻煩。
具體如何使用它進(jìn)行狀態(tài)管理呢?可以看到在對(duì)應(yīng)的布局中需要寫(xiě)上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>
那么,如果某個(gè)子類不想繼承BaseActivity類,如何使用該狀態(tài)管理器呢?代碼中可以這種使用。
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);
04.如何降低偶性和入侵性
讓View狀態(tài)的切換和Activity徹底分離開(kāi),必須把這些狀態(tài)View都封裝到一個(gè)管理類中,然后暴露出幾個(gè)方法來(lái)實(shí)現(xiàn)View之間的切換。 在不同的項(xiàng)目中可以需要的View也不一樣,所以考慮把管理類設(shè)計(jì)成builder模式來(lái)自由的添加需要的狀態(tài)View。
那么如何降低耦合性,讓代碼入侵性低。方便維護(hù)和修改,且移植性強(qiáng)呢?大概具備這樣的條件……
- 可以運(yùn)用在activity或者fragment中
- 不需要在布局中添加LoadingView,而是統(tǒng)一管理不同狀態(tài)視圖,同時(shí)暴露對(duì)外設(shè)置自定義狀態(tài)視圖方法,方便UI特定頁(yè)面定制
- 支持設(shè)置自定義不同狀態(tài)視圖,即使在BaseActivity統(tǒng)一處理狀態(tài)視圖管理,也支持單個(gè)頁(yè)面定制
- 在加載視圖的時(shí)候像異常和空頁(yè)面能否用ViewStub代替,這樣減少繪制,只有等到出現(xiàn)異常和空頁(yè)面時(shí),才將視圖給inflate出來(lái)
- 當(dāng)頁(yè)面出現(xiàn)網(wǎng)絡(luò)異常頁(yè)面,空頁(yè)面等,頁(yè)面會(huì)有交互事件,這時(shí)候可以設(shè)置點(diǎn)擊設(shè)置網(wǎng)絡(luò)或者點(diǎn)擊重新加載等等
05.封裝低入侵性狀態(tài)庫(kù)
5.1 自定義幀布局
首先需要自定義一個(gè)狀態(tài)StateFrameLayout布局,它是繼承FrameLayout。在這個(gè)類中,目前是設(shè)置五種不同狀態(tài)的視圖布局,主要的功能操作是顯示或者隱藏布局。為了后期代碼維護(hù)性,根據(jù)面向?qū)ο蟮乃枷?,類盡量保證單一職責(zé),所以關(guān)于狀態(tài)切換,以及設(shè)置自定義狀態(tài)布局,把這個(gè)功能分離處理,放到一個(gè)StateLayoutManager中處理。
看代碼可知,這個(gè)類的功能非常明確,就是隱藏或者展示視圖作用。
/**
* <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;
/**
* 內(nèi)容id
*/
public static final int LAYOUT_CONTENT_ID = 2;
/**
* 異常id
*/
public static final int LAYOUT_ERROR_ID = 3;
/**
* 網(wǎng)絡(luò)異常id
*/
public static final int LAYOUT_NETWORK_ERROR_ID = 4;
/**
* 空數(shù)據(jù)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);
}
}
/**
* 顯示內(nèi)容
*/
public void showContent() {
if (layoutSparseArray.get(LAYOUT_CONTENT_ID) != null) {
showHideViewById(LAYOUT_CONTENT_ID);
}
}
/**
* 顯示空數(shù)據(jù)
*/
public void showEmptyData(int iconImage, String textTip) {
if (inflateLayout(LAYOUT_EMPTY_DATA_ID)) {
showHideViewById(LAYOUT_EMPTY_DATA_ID);
emptyDataViewAddData(iconImage, textTip);
}
}
/**
* 根據(jù)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);
}
}
}
}
}
/**
* 這個(gè)是處理ViewStub的邏輯,主要有網(wǎng)絡(luò)異常布局,加載異常布局,空數(shù)據(jù)布局
* @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;
}
}
5.2 自定義狀態(tài)管理器
上面狀態(tài)的自定義布局創(chuàng)建出來(lái)了,而且隱藏和展示都做了。那么如何控制設(shè)置自定義視圖布局,還有如何控制不同布局之間切換,那么就需要用到這個(gè)類呢!github.com/yangchong211/YCStateLayout
loadingLayoutResId和contentLayoutResId代表等待加載和顯示內(nèi)容的xml文件
幾種異常狀態(tài)要用ViewStub,因?yàn)樵诮缑鏍顟B(tài)切換中l(wèi)oading和內(nèi)容View都是一直需要加載顯示的,但是其他的3個(gè)只有在沒(méi)數(shù)據(jù)或者網(wǎng)絡(luò)異常的情況下才會(huì)加載顯示,所以用ViewStub來(lái)加載他們可以提高性能。
采用builder模式,十分簡(jiǎn)單,代碼如下所示。創(chuàng)建StateFrameLayout對(duì)象,然后再設(shè)置setStatusLayoutManager,這一步操作是傳遞一個(gè)Manager對(duì)象到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;
//創(chuàng)建幀布局
rootFrameLayout = new StateFrameLayout(this.context);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
rootFrameLayout.setLayoutParams(layoutParams);
//設(shè)置狀態(tài)管理器
rootFrameLayout.setStatusLayoutManager(this);
}
/**
* 顯示loading
*/
public void showLoading() {
rootFrameLayout.showLoading();
}
/**
* 顯示內(nèi)容
*/
public void showContent() {
rootFrameLayout.showContent();
}
/**
* 顯示空數(shù)據(jù)
*/
public void showEmptyData(int iconImage, String textTip) {
rootFrameLayout.showEmptyData(iconImage, textTip);
}
/**
* 顯示空數(shù)據(jù)
*/
public void showEmptyData() {
showEmptyData(0, "");
}
/**
* 顯示空數(shù)據(jù)
*/
public void showLayoutEmptyData(Object... objects) {
rootFrameLayout.showLayoutEmptyData(objects);
}
/**
* 顯示網(wǎng)絡(luò)異常
*/
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;
}
/**
* 自定義網(wǎng)絡(luò)錯(cuò)誤布局
*/
public Builder netWorkErrorView(@LayoutRes int newWorkErrorId) {
netWorkErrorVs = new ViewStub(context);
netWorkErrorVs.setLayoutResource(newWorkErrorId);
return this;
}
/**
* 自定義加載空數(shù)據(jù)布局
*/
public Builder emptyDataView(@LayoutRes int noDataViewId) {
emptyDataVs = new ViewStub(context);
emptyDataVs.setLayoutResource(noDataViewId);
return this;
}
/**
* 自定義加載錯(cuò)誤布局
*/
public Builder errorView(@LayoutRes int errorViewId) {
errorVs = new ViewStub(context);
errorVs.setLayoutResource(errorViewId);
return this;
}
/**
* 自定義加載內(nèi)容正常布局
*/
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;
}
/**
* 為狀態(tài)View顯示隱藏監(jiān)聽(tīng)事件
* @param listener listener
* @return
*/
public Builder onShowHideViewListener(OnShowHideViewListener listener) {
this.onShowHideViewListener = listener;
return this;
}
/**
* 為重試加載按鈕的監(jiān)聽(tīng)事件
* @param onRetryListener listener
* @return
*/
public Builder onRetryListener(OnRetryListener onRetryListener) {
this.onRetryListener = onRetryListener;
return this;
}
/**
* 創(chuàng)建對(duì)象
* @return
*/
public StateLayoutManager build() {
return new StateLayoutManager(this);
}
}
}
5.3 如何管理多種狀態(tài)
大約5種狀態(tài),如何管理這些狀態(tài)?添加到集合中,Android中選用SparseArray比HashMap更省內(nèi)存,在某些條件下性能更好,主要是因?yàn)樗苊饬藢?duì)key的自動(dòng)裝箱(int轉(zhuǎn)為Integer類型),它內(nèi)部則是通過(guò)兩個(gè)數(shù)組來(lái)進(jìn)行數(shù)據(jù)存儲(chǔ)的,一個(gè)存儲(chǔ)key,另外一個(gè)存儲(chǔ)value,為了優(yōu)化性能,它內(nèi)部對(duì)數(shù)據(jù)還采取了壓縮的方式來(lái)表示稀疏數(shù)組的數(shù)據(jù),從而節(jié)約內(nèi)存空間
/**存放布局集合 */
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);
}
//那么哪里從集合中取數(shù)據(jù)呢
public void showContent() {
if (layoutSparseArray.get(LAYOUT_CONTENT_ID) != null) {
showHideViewById(LAYOUT_CONTENT_ID);
}
}
06.封裝庫(kù)極致優(yōu)化點(diǎn)說(shuō)明
6.1 用ViewStub顯示布局
方法里面通過(guò)id判斷來(lái)執(zhí)行不同的代碼,首先判斷ViewStub是否為空,如果為空就代表沒(méi)有添加這個(gè)View就返回false,不為空就加載View并且添加到集合當(dāng)中,然后調(diào)用showHideViewById方法顯示隱藏View,retryLoad方法是給重試按鈕添加事件
注意,即使當(dāng)你設(shè)置了多種不同狀態(tài)視圖,調(diào)用setContentView的時(shí)候,因?yàn)楫惓m?yè)面使用ViewStub,所以在繪制的時(shí)候不會(huì)影響性能的。
/**
* 顯示loading
*/
public void showLoading() {
if (layoutSparseArray.get(LAYOUT_LOADING_ID) != null)
showHideViewById(LAYOUT_LOADING_ID);
}
/**
* 顯示內(nèi)容
*/
public void showContent() {
if (layoutSparseArray.get(LAYOUT_CONTENT_ID) != null)
showHideViewById(LAYOUT_CONTENT_ID);
}
//調(diào)用inflateLayout方法,方法返回true然后調(diào)用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;
}
6.2 處理重新加載邏輯
最后看看重新加載方法
/**
* 重試加載
*/
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();
}
});
}
07.如何使用該封裝庫(kù)
可以自由切換內(nèi)容,空數(shù)據(jù),異常錯(cuò)誤,加載,網(wǎng)絡(luò)錯(cuò)誤等5種狀態(tài)。父類BaseActivity直接暴露5中狀態(tài),方便子類統(tǒng)一管理狀態(tài)切換,這里fragment的封裝和activity差不多。
/**
* ================================================
* 作 者:楊充
* 版 本:1.0
* 創(chuàng)建日期: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();
}
//子類必須重寫(xiě)該方法
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());
}
//正常展示數(shù)據(jù)狀態(tài)
protected void showContent() {
statusLayoutManager.showContent();
}
//加載數(shù)據(jù)為空時(shí)狀態(tài)
protected void showEmptyData() {
statusLayoutManager.showEmptyData();
}
//加載數(shù)據(jù)錯(cuò)誤時(shí)狀態(tài)
protected void showError() {
statusLayoutManager.showError();
}
//網(wǎng)絡(luò)錯(cuò)誤時(shí)狀態(tài)
protected void showNetWorkError() {
statusLayoutManager.showNetWorkError();
}
//正在加載中狀態(tài)
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();
}
//或者添加上監(jiān)聽(tīng)事件
@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() {
//為重試加載按鈕的監(jiān)聽(tīng)事件
}
})
.onShowHideViewListener(new OnShowHideViewListener() {
@Override
public void onShowView(View view, int id) {
//為狀態(tài)View顯示監(jiān)聽(tīng)事件
}
@Override
public void onHideView(View view, int id) {
//為狀態(tài)View隱藏監(jiān)聽(tīng)事件
}
})
.build();
}
//如何切換狀態(tài)呢?
showContent();
showEmptyData();
showError();
showLoading();
showNetWorkError();
//或者這樣操作也可以
statusLayoutManager.showLoading();
statusLayoutManager.showContent();
那么如何設(shè)置狀態(tài)頁(yè)面的交互事件呢?當(dāng)狀態(tài)是加載數(shù)據(jù)失敗時(shí),點(diǎn)擊可以刷新數(shù)據(jù);當(dāng)狀態(tài)是無(wú)網(wǎng)絡(luò)時(shí),點(diǎn)擊可以設(shè)置網(wǎng)絡(luò)。代碼如下所示:
/**
* 點(diǎn)擊重新刷新
*/
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();
}
});
}
/**
* 點(diǎn)擊設(shè)置網(wǎng)絡(luò)
*/
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);
}
});
}
那有些頁(yè)面想要自定義指定的狀態(tài)頁(yè)面UI,又該如何操作呢?倘若有些頁(yè)面想定制狀態(tài)布局,也可以自由實(shí)現(xiàn),很簡(jiǎn)單:
/**
* 自定義加載數(shù)據(jù)為空時(shí)的狀態(tài)布局
*/
private void initEmptyDataView() {
statusLayoutManager.showEmptyData();
//此處是自己定義的狀態(tài)布局
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();
}
});
}
以上就是Android中不同狀態(tài)頁(yè)面管理優(yōu)化技巧詳解的詳細(xì)內(nèi)容,更多關(guān)于Android頁(yè)面管理的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Android應(yīng)用UI開(kāi)發(fā)中Fragment的常見(jiàn)用法小結(jié)
這篇文章主要介紹了Android應(yīng)用UI開(kāi)發(fā)中Fragment的常見(jiàn)用法小結(jié),Fragment的存在是為了解決不同屏幕分辯率的動(dòng)態(tài)和靈活UI設(shè)計(jì),需要的朋友可以參考下2016-02-02
Android輔助功能實(shí)現(xiàn)自動(dòng)搶紅包(附源碼)
本篇文章主要介紹了Android輔助功能實(shí)現(xiàn)自動(dòng)搶紅包(附源碼),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-11-11
Android中的Shape和Selector的結(jié)合使用實(shí)例
這篇文章主要介紹了Android中的Shape和Selector的結(jié)合使用實(shí)例,本文直接給出實(shí)例代碼,需要的朋友可以參考下2015-06-06
Android 屬性動(dòng)畫(huà)ValueAnimator與插值器詳解
這篇文章主要介紹了Android 屬性動(dòng)畫(huà)ValueAnimator與插值器詳解的相關(guān)資料,需要的朋友可以參考下2017-05-05
Android 判斷SIM卡是中國(guó)移動(dòng)\中國(guó)聯(lián)通\中國(guó)電信(移動(dòng)運(yùn)營(yíng)商)
本文給帶來(lái)兩種方法來(lái)判斷sim卡是屬于哪個(gè)運(yùn)營(yíng)商的,要實(shí)現(xiàn)此功能我們需要先獲取手機(jī)的imsi碼然后在判斷,對(duì)此功能感興趣的朋友一起通過(guò)本文學(xué)習(xí)吧2016-09-09
Android編程之控件狀態(tài)配置文件實(shí)例
這篇文章主要介紹了Android編程之控件狀態(tài)配置文件,以實(shí)例形式分析了Android控件狀態(tài)配置文件對(duì)于選中、獲得焦點(diǎn)、按下時(shí)的狀態(tài)等相關(guān)設(shè)置技巧,需要的朋友可以參考下2016-01-01
Android仿QQ好友列表實(shí)現(xiàn)列表收縮與展開(kāi)
這篇文章主要介紹了Android仿QQ好友列表實(shí)現(xiàn)列表收縮與展開(kāi),感興趣的小伙伴們可以參考一下2015-12-12
Android中使用Notification實(shí)現(xiàn)狀態(tài)欄的通知
本文主要介紹了android利用Notification實(shí)現(xiàn)狀態(tài)欄的通知的示例代碼。具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧2017-04-04
Android開(kāi)源堆疊滑動(dòng)控件仿探探效果
這篇文章主要為大家詳細(xì)介紹了Android開(kāi)源堆疊滑動(dòng)控件仿探探效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03

