Skip to content

Instantly share code, notes, and snippets.

View tonnylitao's full-sized avatar
🎯
Focusing

Tonny tonnylitao

🎯
Focusing
View GitHub Profile
class RecyclerAdapter<M : RecyclerItem>(
diffCallback: DiffUtil.ItemCallback<M>,
@LayoutRes val placeholderId: Int?,
private val clickListener: Listener? = null
) : PagedListAdapter<M, ViewHolder<M>>
(diffCallback) {
override fun getItemViewType(position: Int)
= requireNotNull(
getItem(position)?.layoutId ?: placeholderId
){
"item at $position is null"
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int)
inner class ViewHolder(
val binding: ViewDataBinding
): RecyclerView.ViewHolder(binding.root)
override fun onBindViewHolder(
holder: ViewHolder,
position: Int
){
getItem(position)?.run(holder.binding::bind)
}
} //end of RecyclerAdapter
private fun ViewDataBinding.bind(
data class User(
...
) : RecyclerItem {
override val layoutId: Int
get() = R.layout.list_item_user
override val variableId: Int
get() = BR.user
override val dataToBind: Any
class MainFragment:
Fragment(R.layout.fragment_main) {
private val adapter by lazy {
RecyclerAdapter(
RecyclerItem.diffCallback<User>(),
R.layout.list_item_user_placeholder
) { _, _, item ->
data class Comment(
...
) : RecyclerItem {
...
}
data class ComplexModel(
val model: SomeModel
...
) : RecyclerItem {
@tonnylitao
tonnylitao / User.swift
Last active July 1, 2020 12:19
User model
struct User {
var name, email: String?
var likeKiwi = false
var travel = false
var hiking = false
var reading = false
}
@tonnylitao
tonnylitao / KeypathViewMapping.swift
Created June 29, 2020 11:44
KeypathViewMapping.swift
let mapping = [
\User.name: nameField,
\User.email: gmailField,
\User.address: addressField,
\User.travel: travelBtn,
\User.hiking: hikingBtn,
\User.reading: readingBtn,
]
@tonnylitao
tonnylitao / DataBindingEx.swift
Created June 29, 2020 11:50
DataBindingEx.swift
extension DataBinding {
public func update<Value>(_ keyPath: WritableKeyPath<M, Value>, _ value: Value) {
model[keyPath: keyPath] = value
_keyPathViews[keyPath]?.wrappedView?.setValue(value)
}
}