添加setEmptyView
ListView提供了setEmptyView()设置Adapter数据为空时的View视图。RecyclerView虽然没提供直接的API,但是也可以很简单地实现。
- 创建一个继承RecyclerView的类,记为EmptyRecyclerView。
- 通过getRootView().addView(emptyView)将空数据时显示的View添加到当前View的层次结构中。
- 通过AdapterDataObserver监听RecyclerView的数据变化,如果adapter为空,那么隐藏RecyclerView,显示EmptyView。
具体实现如下:
public class EmptyRecyclerView extends RecyclerView{
private View mEmptyView;
private AdapterDataObserver mObserver = new AdapterDataObserver() {
@Override
public void onChanged() {
Adapter adapter = getAdapter();
if(adapter.getItemCount() == 0){
mEmptyView.setVisibility(VISIBLE);
EmptyRecyclerView.this.setVisibility(GONE);
} else{
mEmptyView.setVisibility(GONE);
EmptyRecyclerView.this.setVisibility(VISIBLE);
}
}
public void onItemRangeChanged(int positionStart, int itemCount) {onChanged();}
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {onChanged();}
public void onItemRangeRemoved(int positionStart, int itemCount) {onChanged();}
public void onItemRangeInserted(int positionStart, int itemCount) {onChanged();}
public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {onChanged();}
};
public EmptyRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public void setEmptyView(View view){
this.mEmptyView = view;
((ViewGroup)this.getRootView()).addView(mEmptyView); //加入主界面布局
}
public void setAdapter(RecyclerView.Adapter adapter){
super.setAdapter(adapter);
adapter.registerAdapterDataObserver(mObserver);
mObserver.onChanged();
}
}