Last active
July 13, 2018 06:03
-
-
Save xuhaibahmad/b39f57c9bd9ce6eaa4ec7d39a210df6c to your computer and use it in GitHub Desktop.
A simple RecyclerView subclass that supports providing an empty view which is displayed when the adapter has no data and hidden otherwise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.support.v7.widget.RecyclerView | |
import android.util.AttributeSet | |
import android.view.View | |
/** | |
* Created by zuhaib.ahmad on 2/22/2018. | |
* | |
* Simple RecyclerView subclass that supports providing an empty view (which | |
* is displayed when the adapter has no data and hidden otherwise). | |
*/ | |
class BaseRecyclerView : RecyclerView { | |
var emptyView: View? = null | |
private val dataObserver = object : RecyclerView.AdapterDataObserver() { | |
override fun onChanged() { | |
super.onChanged() | |
updateEmptyView() | |
} | |
} | |
constructor(c: Context) : super(c) | |
constructor(c: Context, attrs: AttributeSet) : super(c, attrs) | |
constructor(c: Context, attrs: AttributeSet, defStyle: Int) : super(c, attrs, defStyle) | |
override fun setAdapter(adapter: RecyclerView.Adapter<*>?) { | |
getAdapter()?.unregisterAdapterDataObserver(dataObserver) | |
adapter?.registerAdapterDataObserver(dataObserver) | |
super.setAdapter(adapter) | |
updateEmptyView() | |
} | |
private fun updateEmptyView() { | |
val showEmptyView = adapter.itemCount == 0 | |
emptyView?.visibility = if (showEmptyView) View.VISIBLE else View.GONE | |
visibility = if (showEmptyView) View.GONE else View.VISIBLE | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment