EmptyRecyclerView.kt
package com.android.widget
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.recyclerview.widget.RecyclerView
class EmptyRecyclerView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr) {
private var emptyView: View? = null;
private val observer=object : AdapterDataObserver(){
override fun onChanged() {
//super.onChanged()
checkIfEmpty()
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
//super.onItemRangeRemoved(positionStart, itemCount)
checkIfEmpty()
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
//super.onItemRangeInserted(positionStart, itemCount)
checkIfEmpty()
}
}
private fun checkIfEmpty(){
emptyView?.let {view ->
adapter?.let { adapter->
val emptyViewVisible = adapter.itemCount == 0
view.visibility=if(emptyViewVisible) View.VISIBLE else View.GONE
visibility =if(emptyViewVisible) View.GONE else View.VISIBLE
}
}
}
override fun setAdapter(newadapter: Adapter<*>?) {
val oldAdapter=adapter
oldAdapter?.let {
it.unregisterAdapterDataObserver(observer)
}
super.setAdapter(newadapter)
newadapter?.let {
it.registerAdapterDataObserver(observer)
}
checkIfEmpty()
}
fun setEmptyView(emptyView:View){
this.emptyView = emptyView
checkIfEmpty()
}
}
XML 文件
<com.android.widget.EmptyRecyclerView
android:id="@+id/recyclerViewQuery"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline"
app:layout_constraintVertical_bias="1.0" />
<TextView
android:id="@+id/textViewNoData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/no_data"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/guideline" />
在代码里面
recyclerViewList.setEmptyView(textViewEmpty)