gpt4 book ai didi

android - 等价于 RecyclerView 中的 ListView.setEmptyView

转载 作者:IT老高 更新时间:2023-10-28 13:08:09 26 4
gpt4 key购买 nike

RecyclerView 中,我想设置一个空 View ,以便在适配器为空时显示。是否有 ListView.setEmptyView() 的等价物? ?

最佳答案

这是一个类似于@dragonborn 的类,但更完整。基于 this gist .

public class EmptyRecyclerView 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 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);
}

void checkIfEmpty() {
if (emptyView != null && getAdapter() != null) {
final boolean emptyViewVisible = getAdapter().getItemCount() == 0;
emptyView.setVisibility(emptyViewVisible ? VISIBLE : GONE);
setVisibility(emptyViewVisible ? GONE : VISIBLE);
}
}

@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();
}
}

关于android - 等价于 RecyclerView 中的 ListView.setEmptyView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27414173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com