StateView 一個(gè)輕量級的控件, 繼承自 View, 吸收了 ViewStub 的一些特性, 初始狀態(tài)下是不可見的, 不占布局位置, 占用內(nèi)存少规婆。 當(dāng)進(jìn)行操作顯示空/重試/加載視圖后, 該視圖才會被添加到布局中。
使用方法
1.
//在 app 下的 build.gradle 中添加以下依賴
compile 'com.github.nukc.stateview:library:1.5.4'
// animator providers
compile 'com.github.nukc.stateview:animations:1.0.1'
2.
//將 StateView 控件添加到 xml 文件中
<com.github.nukc.stateview.StateView
android:id="@+id/stateView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/ll"
tools:visibility="gone" />
3.
//在 Activity中實(shí)例化StateView
private StateView mStateView;
mStateView = (StateView) findViewById(R.id.stateView);
注入到 Activity
mStateView = StateView.inject(Activity activity);
注入到 ViewGroup
mStateView = StateView.inject(ViewGroup parent);
mStateView = StateView.inject(ViewGroup parent, boolean hasActionBar);
// 如果 View 不是 ViewGroup冯袍,則會注入到 View 的 parent 中
mStateView = StateView.inject(View view);
mStateView = StateView.inject(View view, boolean hasActionBar);
包裹指定的 View犬钢,這個(gè)會增加層次
mStateView = StateView.wrap(View view);
4.
//切換頁面
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnInEmpty:
//切換為 無數(shù)據(jù) 頁面
mStateView.showEmpty();
break;
case R.id.btnInRetry:
//切換為 刷新 頁面
mStateView.showRetry();
break;
case R.id.btnRemove:
//切換為 內(nèi)容 頁面
mStateView.showContent();
break;
case R.id.btnRemove:
//切換為 加載 頁面
mStateView.showLoading();
break;
}
}
顯示空視圖: mStateView.showEmpty();
顯示加載視圖: mStateView.showLoading();
顯示重試視圖: mStateView.showRetry();
顯示內(nèi)容: mStateView.showContent();
5.
//設(shè)置點(diǎn)擊事件
mStateView.setOnRetryClickListener(new StateView.OnRetryClickListener() {
@Override
public void onRetryClick() {
//do something, no need to call showLoading()
//不需要調(diào)用showLoading()方法, StateView自會調(diào)用
}
});
設(shè)置自定義視圖:
全局設(shè)置辦法:在自己項(xiàng)目的layout下新建, 名字跟StateView默認(rèn)layout一樣即可(也不用代碼設(shè)置). 默認(rèn)layout的名字:base_empty/base_retry/base_loading.
單頁面設(shè)置:layout名字不一樣, 然后再代碼設(shè)置.
setEmptyResource(@LayoutRes int emptyResource)
setRetryResource(@LayoutRes int retryResource)
setLoadingResource(@LayoutRes int loadingResource)
動(dòng)畫切換
// 默認(rèn) provider 是 null苍鲜,即默認(rèn)不提供動(dòng)畫切換
// 如果需要,設(shè)置一個(gè)就可以了
setAnimatorProvider(AnimatorProvider provider)
漸變縮放: FadeScaleAnimatorProvider
卡片翻轉(zhuǎn): FlipAnimatorProvider
左右滑動(dòng): SlideAnimatorProvider
兼容沉浸式全屏模式
/**
* @return statusBarHeight
對于是沉浸式全屏模式下的玷犹,可以使用此方法補(bǔ)上 statusBar 的 height混滔,從而不覆蓋 toolbar
*/
private int getStatusBarHeight() {
int height = 0;
int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resId > 0) {
height = getResources().getDimensionPixelSize(resId);
}
return height;
}
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) mStateView.getLayoutParams();
layoutParams.topMargin += getStatusBarHeight()