Equivalent of ListView.setEmptyView in RecyclerView

前端 未结 13 1699
孤街浪徒
孤街浪徒 2020-11-30 17:44

In RecyclerView, I want to set an empty view to be shown when the adapter is empty. Is there an equivalent of ListView.setEmptyView()?

13条回答
  •  悲哀的现实
    2020-11-30 18:13

    My version, based on https://gist.github.com/adelnizamutdinov/31c8f054d1af4588dc5c

    public class EmptyRecyclerView extends RecyclerView {
        @Nullable
        private View emptyView;
    
        public EmptyRecyclerView(Context context) { super(context); }
    
        public EmptyRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); }
    
        public EmptyRecyclerView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        private void checkIfEmpty() {
            if (emptyView != null && getAdapter() != null) {
                emptyView.setVisibility(getAdapter().getItemCount() > 0 ? GONE : VISIBLE);
            }
        }
    
        private final AdapterDataObserver observer = new AdapterDataObserver() {
            @Override
            public void onChanged() {
                checkIfEmpty();
            }
    
            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                checkIfEmpty();
            }
    
            @Override
            public void onItemRangeRemoved(int positionStart, int itemCount) {
                checkIfEmpty();
            }
        };
    
        @Override
        public void setAdapter(@Nullable Adapter adapter) {
            final Adapter oldAdapter = getAdapter();
            if (oldAdapter != null) {
                oldAdapter.unregisterAdapterDataObserver(observer);
            }
            super.setAdapter(adapter);
            if (adapter != null) {
                adapter.registerAdapterDataObserver(observer);
            }
            checkIfEmpty();
        }
    
        @Override
        public void setVisibility(int visibility) {
            super.setVisibility(visibility);
            if (null != emptyView && (visibility == GONE || visibility == INVISIBLE)) {
                emptyView.setVisibility(GONE);
            } else {
                checkIfEmpty();
            }
        }
    
        public void setEmptyView(@Nullable View emptyView) {
            this.emptyView = emptyView;
            checkIfEmpty();
        }
    }
    

提交回复
热议问题