Jack Guo
Jack Guo

Reputation: 4664

RecyclerView data binding with custom item configuration

My recycler view has two types of item view. One type of them has MPAndroidChart in it. I need to do some chart view configuration that cannot be done in XML. How can I do it given that I am using RecyclerView data binding with a single base view holder (as recommended by George Mount) ?

open class BaseViewHolder(private val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {
    fun bind(obj: Any) {
        binding.setVariable(BR.obj, obj)
        binding.executePendingBindings()
    }
}

abstract class BaseAdapter : RecyclerView.Adapter<BaseViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val binding = DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, viewType, parent, false)
        return BaseViewHolder(binding)
    }
    override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
        val obj = getObjForPosition(position)
        holder.bind(obj)
    }
    override fun getItemViewType(position: Int): Int {
        return getLayoutIdForPosition(position)
    }
    protected abstract fun getObjForPosition(position: Int): Any
    protected abstract fun getLayoutIdForPosition(position: Int): Int
}

Upvotes: 1

Views: 619

Answers (1)

Raymond Arteaga
Raymond Arteaga

Reputation: 4673

You can still access

holder.itemView.myChartViewId.doSomeStuff()

on the onBindViewHolder() call.

You can also implement a function to "initialize" your charts in your view holder like this:

open class BaseViewHolder(private val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {
    fun bind(obj: Any) {
        binding.setVariable(BR.obj, obj)
        binding.executePendingBindings()
    }

    fun initCharts() {
        if (itemView.myChartViewId == null) return
        itemView.myChartViewId.doSomwStuff()
    }
}

and call it whenever you need.

Upvotes: 3

Related Questions