Last active
January 13, 2022 07:11
-
-
Save Morteza-QN/975ad0ca5c280299d6cde5b060166de3 to your computer and use it in GitHub Desktop.
implementation abstract adapter recyclerView by databinding android in kotlin
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
import android.annotation.SuppressLint | |
import android.view.LayoutInflater | |
import android.view.ViewGroup | |
import androidx.annotation.LayoutRes | |
import androidx.databinding.DataBindingUtil | |
import androidx.databinding.ViewDataBinding | |
import androidx.recyclerview.widget.RecyclerView | |
import com.kcd.karchidari.BR | |
import timber.log.Timber | |
import java.util.* | |
abstract class AdapterX<T : ViewDataBinding, G : Any>( | |
@LayoutRes private val layoutResId: Int, | |
private val callback: EventListener<G>? = null, | |
// private val callback: (G) -> Unit, | |
) : RecyclerView.Adapter<AdapterX<T, G>.ViewHolderX>() { | |
protected var items: List<G> = ArrayList<G>() | |
private var _binding: T? = null | |
protected val binding: T get() = _binding!! | |
open fun T.initialize(item: G, position: Int) {} | |
open fun T.initialize(item: G, callback: EventListener<G>?) {} | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolderX { | |
val inflater = LayoutInflater.from(parent.context) | |
_binding = DataBindingUtil.inflate(inflater, layoutResId, parent, false) | |
// _binding?.lifecycleOwner = parent.findViewTreeLifecycleOwner() | |
return ViewHolderX(binding) | |
} | |
override fun onBindViewHolder(holder: ViewHolderX, position: Int) = holder.bind(items[position], callback) | |
override fun getItemCount(): Int = items.size | |
inner class ViewHolderX(private val binding: T) : RecyclerView.ViewHolder(binding.root) { | |
fun bind(item: G, callback: EventListener<G>?) { | |
try { | |
binding.setVariable(BR.item, item) | |
binding.setVariable(BR.callback, callback) | |
} catch (e: Exception) { | |
Timber.e("must be define variable in layout by name=item ,callback \n $e") | |
} | |
binding.initialize(item, adapterPosition) | |
binding.initialize(item, callback) | |
binding.executePendingBindings() | |
} | |
} | |
@SuppressLint("NotifyDataSetChanged") | |
fun updateItems(items: List<G>?) { | |
this.items = items ?: emptyList() | |
notifyDataSetChanged() | |
} | |
interface EventListener<G> { | |
fun onClickItem(item: G) {} | |
fun onLongClickItem(item: G): Boolean = false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment