【问题标题】:Empty View on a RecyclerViewRecyclerView 上的空视图
【发布时间】: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


【解决方案1】:

我更新了你的代码:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:name="com.github.jlcarveth.grocer.layout.fragment.GroceryListFragment"
android:layout_width="match_parent"
tools:context="com.github.jlcarveth.grocer.layout.fragment.GroceryListFragment"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
    android:id="@+id/grocery_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="0dp"
    app:layoutManager="LinearLayoutManager"
    tools:listitem="@layout/grocery_item" />

<TextView
    android:id="@+id/empty_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:visibility="gone"
    android:text="NO DATA AVAILABLE" />
</FrameLayout>

你的片段:

 @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);
    TextView emptyView = (TextView)view.findViewById(R.id.empty_view);

    dh = new DatabaseHandler(view.getContext());

    dataset = dh.getGroceries();


     Context context = view.getContext();
     RecyclerView recyclerView = (RecyclerView) rv;
     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(recyclerView);

    DividerItemDecoration div = new DividerItemDecoration(recyclerView.getContext(),
            DividerItemDecoration.VERTICAL);

    recyclerView.addItemDecoration(div);


    if (dataset.isEmpty()){
        recyclerView.setVisibility(View.GONE);
         emptyView.setVisibility(View.VISIBLE);
    } else {
         recyclerView.setVisibility(View.VISIBLE);
         emptyView.setVisibility(View.GONE);
    }



    return view;
}

【讨论】:

  • 这是对我当前代码进行最简单更改的有效解决方案!
【解决方案2】:

在你的布局中添加一个文本视图。与 RecyclerView 同级

<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 也是空的。在这种情况下,消息会出现在屏幕上。如果没有,请更改其可见性:

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

【讨论】:

  • 如果我尝试将 TextView 放在与 RecyclerView 相同的级别上,则会收到多个根标签的错误
  • 把这两个放在一个RelativeLayout里面。
  • 然后把它们放在一个布局中,这样它们都不是根
【解决方案3】:

此答案适用于在其 Android 项目中使用 Kotlin 和数据绑定的开发人员。

custom_recyclerview_empty_support.xml

<?xml version="1.0" encoding="utf-8"?>
<layout 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">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Recycler view -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!-- Empty view -->
    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/empty_text_view"
        style="@style/TextAppearance.MaterialComponents.Body1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@color/white_light"
        android:gravity="center"
        android:textColor="@color/black_light"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Empty View" />

    <!-- Retry view -->
    <androidx.appcompat.widget.LinearLayoutCompat
        android:id="@+id/retry_linear_layout_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@color/white_light"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/retry_text_view"
            style="@style/TextAppearance.MaterialComponents.Body1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/views_pad_horizontal"
            android:layout_marginTop="@dimen/views_pad_vertical"
            android:layout_marginEnd="@dimen/views_pad_horizontal"
            android:layout_marginBottom="@dimen/views_pad_vertical"
            android:gravity="center"
            tools:text="Retry View" />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/retry_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/retry_button" />
    </androidx.appcompat.widget.LinearLayoutCompat>

    <!--  Loading view -->
    <FrameLayout
        android:id="@+id/loading_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@color/white_light"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ProgressBar
            android:id="@+id/progress_bar"
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" />
    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

我使用这个自定义 RecyclerView 类的片段类

     <app.ui.widgets.RecyclerViewEmptySupport
            android:id="@+id/my_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

创建自定义 RecyclerView 类:

class RecyclerViewEmptySupport(context: Context, attrs: AttributeSet) :
ConstraintLayout(context, attrs) {

private val binding: CustomRecyclerviewEmptySupportBinding
val recyclerView: RecyclerView

init {
    this.binding =
        CustomRecyclerviewEmptySupportBinding.inflate(LayoutInflater.from(context), this, true)
    this.recyclerView = binding.recyclerView
}

fun updateViews(
    loading: Boolean = false,
    retry: Boolean = false,
    empty: Boolean = false,
    success: Boolean = false
) {
    binding.recyclerView.setVisibleOrGone(success)
    binding.emptyTextView.setVisibleOrGone(empty)
    binding.retryLinearLayoutView.setVisibleOrGone(retry)
    binding.loadingView.setVisibleOrGone(loading)
}

// Empty view
fun showEmptyMessage(message: String) {
    updateViews(empty = true)
    binding.emptyTextView.text = message
}

// Retry view
fun showRetryView(message: String, callback: () -> Unit) {
    updateViews(retry = true)

    binding.retryTextView.text = message
    binding.retryButton.setOnClickListener { callback() }
}
}

Fragment/Activity 类可以管理 Views 的可见性并将数据设置为视图,如下所示:

要调用api时,调用这段代码,

 binding.myRecyclerView.updateViews(loading = true)
 getDataFromRepository()

当api响应数据为空时,调用这个,

binding.myRecyclerView.showEmptyMessage("No Items Message")

当api中有数据时,调用this,

 list.addAll(apiList)
 adapter.notifyDataSetChanged()

 binding.myRecyclerView.updateViews(success = true)

当api响应出现错误时,调用这个

 binding.myRecyclerView.showRetryView("Unable to get data at the moment.") { getDataFromRepository() }

【讨论】:

    【解决方案4】:

    为什么不选择相对布局。

    <Relative layout>
        <Recycler View/>
    
        <Text View/>
    </Relative layout
    

    因为array 是空的

      RecyclerView.GONE
       TextView.VISIBLE
    

    如果array 有一些数据

      RecyclerView.VISIBLE
      TextView.GONE
    

    就我而言,我只关注这个。

    如果不行,我会把我的代码发给你。

    【讨论】:

    • 它对我不起作用
    【解决方案5】:

    当我遇到这个问题时,我在网上冲浪时发现了有用的 gist https://gist.github.com/sheharyarn/5602930ad84fa64c30a29ab18eb69c6e

    这里展示了如何通过定义数据观察者以优雅的方式实现空视图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多