【发布时间】:2017-11-21 16:12:21
【问题描述】:
在我正在开发的应用程序中,我使用 Recycler View 来显示项目列表。当列表为空时,我希望列表显示一些视图(例如,文本视图)。我知道使用 ListViews,可以调用setEmptyView,但 RecyclerView 没有这种方法。
我尝试将视图的可见性设置为 GONE,并在 RecyclerView 数据集为空时使其可见,但是将任何视图添加到定义了 RecyclerView 的布局文件会导致错误:
Attempt to invoke virtual method 'boolean
android.support.v7.widget.RecyclerView$ViewHolder.shouldIgnore()' on a null
object reference
我正在做的最好的方法是什么?
有关更多信息,RecyclerView 保存在 Fragment 中,并且布局在 onCreateView 函数中膨胀。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_grocerylist, container, false);
rv = view.findViewById(R.id.grocery_list);
dh = new DatabaseHandler(view.getContext());
dataset = dh.getGroceries();
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
recyclerView.setLayoutManager(new LinearLayoutManager(context));
adapter = new GroceryListRecyclerViewAdapter(dataset,mListener,this);
recyclerView.setAdapter(adapter);
}
ItemTouchHelper.Callback callback = new SimpleTouchHelperCallback(adapter);
ith = new ItemTouchHelper(callback);
ith.attachToRecyclerView(rv);
DividerItemDecoration div = new DividerItemDecoration(rv.getContext(),
DividerItemDecoration.VERTICAL);
rv.addItemDecoration(div);
return view;
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/grocery_list" android:name="com.github.jlcarveth.grocer.layout.fragment.GroceryListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
app:layoutManager="LinearLayoutManager" tools:context="com.github.jlcarveth.grocer.layout.fragment.GroceryListFragment" tools:listitem="@layout/grocery_item"/>
【问题讨论】:
-
你能把你的活动或片段吗?
-
这不是一个完整的句子。 ^^^
-
使用片段代码和 xml 布局更新您的答案
-
我把答案放在下面:)
-
使用AdapterDataObserver,看这个链接stackoverflow.com/a/52716769/4797289
标签: android android-recyclerview