如何使用 RecyclerView 显示空视图? [英] How to show an empty view with a RecyclerView?
问题描述
我习惯于在布局文件中放置一个特殊的视图,如ListActivity<中所述的/code> 文档在没有数据时显示.此视图的 ID 为
"android:id/empty"
.
I am used to put an special view inside the layout file as described in the ListActivity
documentation to be displayed when there is no data. This view has the id "android:id/empty"
.
<TextView
android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/no_data" />
我想知道如何使用新的 RecyclerView
?
I wonder how this can be done with the new RecyclerView
?
推荐答案
在定义 RecyclerView
的相同布局上,添加 TextView
:
On the same layout where is defined the RecyclerView
, add the TextView
:
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
<TextView
android:id="@+id/empty_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
android:text="@string/no_data_available" />
在 onCreate
或相应的回调中,您检查提供 RecyclerView
的数据集是否为空.如果数据集为空,则 RecyclerView
也为空.在这种情况下,消息会出现在屏幕上.如果没有,请更改其可见性:
At the onCreate
or the appropriate callback you check if the dataset that feeds your RecyclerView
is empty.
If the dataset is empty, the RecyclerView
is empty too. In that case, the message appears on the screen.
If not, change its visibility:
private RecyclerView recyclerView;
private TextView emptyView;
// ...
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
emptyView = (TextView) rootView.findViewById(R.id.empty_view);
// ...
if (dataset.isEmpty()) {
recyclerView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
}
else {
recyclerView.setVisibility(View.VISIBLE);
emptyView.setVisibility(View.GONE);
}
这篇关于如何使用 RecyclerView 显示空视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!