Home > Software design >  How to display a TextView when Recycler View is empty?
How to display a TextView when Recycler View is empty?

Time:10-15

I would like to display a textView when my RecyclerView is empty. I prepared this function but it doesn't work. I believe I should get the list from RecyclerView but I don't really know how. I am in a fragment.

XML:

<androidx.recyclerview.widget.RecyclerView
        android:id="@ id/recycler_view_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="visible"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/item_list" />

 <TextView
        android:id="@ id/tv_no_records"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="@string/nothing_to_display"
        android:textSize="16sp"
        android:visibility="gone" />

Fragment:

private fun displayList() {

    val list = listOf<Shoe>()
    if (list.isEmpty()) {
        binding.recyclerViewList.visibility = View.VISIBLE
        binding.tvNoRecords.visibility = View.GONE
    } else {
        binding.recyclerViewList.visibility = View.GONE
        binding.tvNoRecords.visibility = View.VISIBLE
    }
}

Adding the shoe (in ViewModel):

fun addShoe(shoe: Shoe) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.addShoes(shoe)
        }
    }

Many thanks, Anna

CodePudding user response:

The conditions are inverted. When list is empty you are showing recyclerView and vice versa. Simply use a not check. Consider below:

private fun displayList() {

    val list = listOf<Shoe>()
    if (list.isNotEmpty()) {
        binding.recyclerViewList.visibility = View.VISIBLE
        binding.tvNoRecords.visibility = View.GONE
    } else {
        binding.recyclerViewList.visibility = View.GONE
        binding.tvNoRecords.visibility = View.VISIBLE
    }
}
  • Related