为了账号安全,请及时绑定邮箱和手机立即绑定

如何给RecyclerView设置一个emptyView?

如何给RecyclerView设置一个emptyView?

斯蒂芬大帝 2019-03-21 18:19:05
网上这些资料好像比较少,有的我也不太懂,还请大神们指点一个简单易懂的。
查看完整描述

2 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

设置一个Recyclerview的平级view,平时把它GONE掉,recyclerview的item为0时把它visible出来不久好了么


查看完整回答
反对 回复 2019-04-24
?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

给楼主之前写的代码,将RecycleView 重写成如下:


public class RecyclerViewEmptySupport extends RecyclerView {


    private View emptyView;

    final private 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();

        }

    };


    public RecyclerViewEmptySupport(Context context) {

        super(context);

    }


    public RecyclerViewEmptySupport(Context context, AttributeSet attrs) {

        super(context, attrs);

    }


    public RecyclerViewEmptySupport(Context context, AttributeSet attrs, int defStyle) {

        super(context, attrs, defStyle);

    }


    @Override

    public void setAdapter(Adapter adapter) {

        final Adapter oldAdapter = getAdapter();

        if (oldAdapter != null) {

            oldAdapter.unregisterAdapterDataObserver(observer);

        }

        super.setAdapter(adapter);

        if (adapter != null) {

            adapter.registerAdapterDataObserver(observer);

        }


        checkIfEmpty();

    }


    public void setEmptyView(View emptyView) {

        this.emptyView = emptyView;

        checkIfEmpty();

    }


    void checkIfEmpty() {

        if (emptyView != null && getAdapter() != null) {

            final boolean emptyViewVisible = getAdapter().getItemCount() == 0;

            emptyView.setVisibility(emptyViewVisible ? VISIBLE : GONE);

            setVisibility(emptyViewVisible ? GONE : VISIBLE);

        }

    }

}

外部调用的时候执行mRecyclerView.setEmptyView(mEmptyView);即可。


查看完整回答
反对 回复 2019-04-24
  • 2 回答
  • 0 关注
  • 1253 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号