Skip to content

Instantly share code, notes, and snippets.

@guness
Created February 19, 2018 14:11
Show Gist options
  • Save guness/df12d8cc4f595af1395f4a1f5bca5f00 to your computer and use it in GitHub Desktop.
Save guness/df12d8cc4f595af1395f4a1f5bca5f00 to your computer and use it in GitHub Desktop.
Custom PagedListAdapter with add support on top
/**
* Created by guness on 7.02.2018.
*/
class CommentAdapter(private val fragment: SGFragment) : RecyclerView.Adapter<CommentViewHolder>() {
private val mCustomList = ArrayList<Comment>()
private val mListener = object : ListUpdateCallback {
override fun onChanged(position: Int, count: Int, payload: Any?) {
notifyItemRangeChanged(paged(position), count, payload)
}
override fun onMoved(fromPosition: Int, toPosition: Int) {
notifyItemMoved(paged(fromPosition), paged(toPosition))
}
override fun onInserted(position: Int, count: Int) {
notifyItemRangeInserted(paged(position), count)
}
override fun onRemoved(position: Int, count: Int) {
notifyItemRangeRemoved(paged(position), count)
}
}
private val mHelper = PagedListAdapterHelper(mListener, ListAdapterConfig.Builder<Comment>().setDiffCallback(diffCallback).build())
private fun paged(position: Int) = position - mCustomList.size
override fun getItemCount(): Int {
return mHelper.itemCount + mCustomList.size
}
private fun getItem(position: Int): Comment? {
return if (mCustomList.size > position) {
mCustomList[position]
} else {
mHelper.currentList?.get(paged(position))
}
}
fun setList(list: PagedList<Comment>?) {
mCustomList.clear()
mHelper.setList(list)
}
fun addComment(comment: Comment) {
mCustomList.add(0, comment)
notifyItemInserted(0)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommentViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_comment, parent, false)
return CommentViewHolder(itemView, fragment)
}
override fun onBindViewHolder(holder: CommentViewHolder, position: Int) {
holder.bind(getItem(position))
}
companion object {
private val diffCallback = object : DiffCallback<Comment>() {
override fun areItemsTheSame(oldItem: Comment, newItem: Comment): Boolean = oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Comment, newItem: Comment): Boolean {
return oldItem.id == newItem.id &&
oldItem.content == newItem.content &&
oldItem.user?.id == newItem.user?.id &&
oldItem.user?.name == newItem.user?.name &&
oldItem.user?.avatar == newItem.user?.avatar
}
}
}
}
@kateile
Copy link

kateile commented Sep 12, 2018

Can you share PagedListAdapterHelper

@yadavraju
Copy link

Can you share PagedListAdapterHelper

@mochadwi
Copy link

Can you share PagedListAdapterHelper

+1

cc @guness

@Osamasaqr84
Copy link

Can you share PagedListAdapterHelper

@guness
Copy link
Author

guness commented Mar 29, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment