2020-11-23 EmptyRecyclerView.kt kotlin 代码

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)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容