StateView 一個輕量級的控件, 繼承自 View, 吸收了 ViewStub 的一些特性, 初始狀態下是不可見的, 不占布局位置, 占用內存少。 當進行操作顯示空/重試/加載視圖后, 該視圖才會被添加到布局中。
使用方法
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中實例化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,這個會增加層次
mStateView = StateView.wrap(View view);
4.
//切換頁面
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnInEmpty:
//切換為 無數據 頁面
mStateView.showEmpty();
break;
case R.id.btnInRetry:
//切換為 刷新 頁面
mStateView.showRetry();
break;
case R.id.btnRemove:
//切換為 內容 頁面
mStateView.showContent();
break;
case R.id.btnRemove:
//切換為 加載 頁面
mStateView.showLoading();
break;
}
}
顯示空視圖: mStateView.showEmpty();
顯示加載視圖: mStateView.showLoading();
顯示重試視圖: mStateView.showRetry();
顯示內容: mStateView.showContent();
5.
//設置點擊事件
mStateView.setOnRetryClickListener(new StateView.OnRetryClickListener() {
@Override
public void onRetryClick() {
//do something, no need to call showLoading()
//不需要調用showLoading()方法, StateView自會調用
}
});
設置自定義視圖:
全局設置辦法:在自己項目的layout下新建, 名字跟StateView默認layout一樣即可(也不用代碼設置). 默認layout的名字:base_empty/base_retry/base_loading.
單頁面設置:layout名字不一樣, 然后再代碼設置.
setEmptyResource(@LayoutRes int emptyResource)
setRetryResource(@LayoutRes int retryResource)
setLoadingResource(@LayoutRes int loadingResource)
動畫切換
// 默認 provider 是 null,即默認不提供動畫切換
// 如果需要,設置一個就可以了
setAnimatorProvider(AnimatorProvider provider)
漸變縮放: FadeScaleAnimatorProvider
卡片翻轉: FlipAnimatorProvider
左右滑動: SlideAnimatorProvider
兼容沉浸式全屏模式
/**
* @return statusBarHeight
對于是沉浸式全屏模式下的,可以使用此方法補上 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()