Skip to content

Instantly share code, notes, and snippets.

@Flywith24
Last active February 27, 2020 06:00
Show Gist options
  • Save Flywith24/f558846794705ec54af1144d1b75a764 to your computer and use it in GitHub Desktop.
Save Flywith24/f558846794705ec54af1144d1b75a764 to your computer and use it in GitHub Desktop.
DataBindingAdapter基类
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.whdx.market.base
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.AsyncDifferConfig
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
/**
* A generic RecyclerView adapter that uses Data Binding & DiffUtil.
*
* @param <T> Type of the items in the list
* @param <V> The type of the ViewDataBinding
</V></T> */
abstract class DataBindingListAdapter<T, V : ViewDataBinding>(
diffCallback: DiffUtil.ItemCallback<T>
) : ListAdapter<T, DataBindingViewHolder<V>>(
AsyncDifferConfig.Builder<T>(diffCallback)
.build()
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataBindingViewHolder<V> {
val binding = createBinding(parent)
return DataBindingViewHolder(binding)
}
protected abstract fun createBinding(parent: ViewGroup): V
override fun onBindViewHolder(holder: DataBindingViewHolder<V>, position: Int) {
bind(holder.binding, getItem(position))
holder.binding.executePendingBindings()
}
protected abstract fun bind(binding: V, item: T)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment