Created
November 13, 2021 10:14
-
-
Save seoft/a7414b16fbb020bf449610f1f3646e03 to your computer and use it in GitHub Desktop.
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
data class BindingItem<ITEM>(@LayoutRes val type: Int, val item: ITEM) | |
fun <T> T.toBindingItem(@LayoutRes type: Int): BindingItem<T> { | |
return BindingItem(type, this) | |
} |
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
open class DataBindingAdapter<ITEM>( | |
private val bindingVariableId: Int? = null, | |
private val variables: Map<Int, Any>? = null, | |
diffUtil: DiffUtil.ItemCallback<BindingItem<ITEM>> | |
) : androidx.recyclerview.widget.ListAdapter<BindingItem<ITEM>, | |
BindViewHolder<BindingItem<ITEM>>>(diffUtil) { | |
override fun onCreateViewHolder( | |
parent: ViewGroup, | |
viewType: Int | |
): BindViewHolder<BindingItem<ITEM>> { | |
return DataBindingViewHolder(viewType, parent, bindingVariableId, variables) | |
} | |
override fun onBindViewHolder(holder: BindViewHolder<BindingItem<ITEM>>, position: Int) { | |
holder.bind(getItem(position)) | |
} | |
override fun getItemViewType(position: Int): Int { | |
return getItem(position).type | |
} | |
} |
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
open class DataBindingViewHolder<ITEM>( | |
@LayoutRes layoutResId: Int, | |
parent: ViewGroup, | |
private val bindingVariableId: Int?, | |
variables: Map<Int, Any>? | |
) : BindViewHolder<BindingItem<ITEM>>( | |
LayoutInflater.from(parent.context).inflate(layoutResId, parent, false) | |
) { | |
private val binding: ViewDataBinding? = DataBindingUtil.bind(itemView) | |
init { | |
variables?.let { | |
for (entry in variables) { | |
binding?.setVariable(entry.key, entry.value) | |
} | |
} | |
} | |
override fun bind(item: BindingItem<ITEM>) { | |
binding ?: return | |
binding.setVariable(bindingVariableId ?: return, item.item) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment