EmptyRecyclerView.kt 1.38 KB
Newer Older
赵鹏翔's avatar
赵鹏翔 committed
1
package com.miya.fastcashier.widget
赵鹏翔's avatar
赵鹏翔 committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.recyclerview.widget.RecyclerView

/**
 * 作者:Leon
 * 时间:2017/3/17 13:44
 */
class EmptyRecyclerView : RecyclerView {

    private var mEmptyView: View? = null

    constructor(context: Context?) : super(context!!) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(
        context!!, attrs
    ) {
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
        context!!, attrs, defStyle
    ) {
    }

    /**
     * 根据数据源判断是否显示空白view
     */
    private fun checkIfEmpty() {
        if (mEmptyView != null || adapter != null) {
            mEmptyView!!.visibility =
                if (adapter!!.itemCount > 0) GONE else VISIBLE
        }
    }

    fun setmEmptyView(mEmptyView: View?) {
        this.mEmptyView = mEmptyView
        checkIfEmpty()
    }

    override fun setAdapter(adapter: Adapter<*>?) {
        val adapterOld = getAdapter()
        adapterOld?.unregisterAdapterDataObserver(observer)
        super.setAdapter(adapter)
        adapter?.registerAdapterDataObserver(observer)
    }

    var observer: AdapterDataObserver = object : AdapterDataObserver() {
        override fun onChanged() {
            super.onChanged()
            checkIfEmpty()
        }
    }
}