Skip to content

Instantly share code, notes, and snippets.

@christianb
Last active June 2, 2019 11:44
Show Gist options
  • Save christianb/104a50e7a21e115d56e56bfa7a4d08f1 to your computer and use it in GitHub Desktop.
Save christianb/104a50e7a21e115d56e56bfa7a4d08f1 to your computer and use it in GitHub Desktop.
ViewHolder easy view inflation
open class BaseRecyclerViewHolder(@LayoutRes layoutRes: Int, viewGroup: ViewGroup) : RecyclerView.ViewHolder(inflate(layoutRes, viewGroup)) { // Use the private companion function inflate() for getting a view instance.
companion object {
fun inflate(@LayoutRes layoutRes: Int, viewGroup: ViewGroup): View {
return LayoutInflater.from(viewGroup.context).inflate(layoutRes, viewGroup, false)
}
}
}
/**
* A ViewHolder should know its own layout to inflate.
* You just need to pass the ViewGroup (you are getting from your Adapter onCreateViewHolder().
* Extending the BaseViewHolder you pass the layout to inflate and the viewGroup.
*/
class MyViewHolder(viewGroup: ViewGroup) : BaseViewHolder(R.layout.my_viewholder, viewGroup)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment