Created
December 28, 2018 10:00
-
-
Save abhinav272/330c7e14ce565dfc1767465cfb84f090 to your computer and use it in GitHub Desktop.
RecyclerViewAdapter converted to PagedListAdapter
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
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 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment