I know The ListAdpater extends a recyclerview adapter. And for initializing items, I use submitList method. the parameter in submitList method is defined like this, typed list.
public void submitList(@Nullable List<T> list) {
mDiffer.submitList(list);
}
I can't remove or add items. So I tried using arraylist variable for adding and removing, and casted it to List. But I'm not sure this is the good way... Because arraylist is not good to add or remove items. Is there other way?
Delete item from ListAdapter. (Kotlin)
fun removeItem(position: Int){
val currentList = adapter.currentList.toMutableList()
currentList.removeAt(position)
adapter.submitList(currentList)
}
Tested and working fine.
MyAdapter
class FavoritesAdapter(
private val listeners: OnFavoriteDetailPage,
private val itemClick: (title: String, price: String) -> Unit) :ListAdapter<Favorites, FavoritesAdapter.RecyclerViewHolder>(ListComparator()) {
//bind the recycler list items
inner class RecyclerViewHolder(val binding: FavoriteListBinding) :
RecyclerView.ViewHolder(binding.root) {
@SuppressLint("SetTextI18n")
fun bind(list: Favorites) {
binding.deal.text = "Deal " + list.id.toString()
binding.price.text = "Ghc " + list.price
binding.pizzaSize.text = list.size.toString()
binding.posterBanner.load(list.imgUrl)
}
}
inflate the List
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
return RecyclerViewHolder(
FavoriteListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
)
}
//bind the model list the recycler list
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {
val getItemPosition = getItem(position)
holder.bind(getItemPosition)
Glide.with(holder.itemView.context).load(getItemPosition.imgUrl)
.into(holder.binding.posterBanner)
holder.binding.addCart.setOnClickListener {
itemClick("Deal ${getItemPosition.id}", getItemPosition.price)
}
holder.itemView.setOnClickListener {
listeners.viewDetail(getItemPosition)
}
holder.binding.favoriteHeart.setOnClickListener {
listeners.onItemRemoveClick(getItemPosition.id)
}
}
class ListComparator : DiffUtil.ItemCallback<Favorites>() {
override fun areItemsTheSame(oldItem: Favorites, newItem: Favorites): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: Favorites, newItem: Favorites): Boolean {
return oldItem.id == newItem.id
}
}
interface OnFavoriteDetailPage {
fun viewDetail(favorites: Favorites)
fun onItemRemoveClick(position: Int)
}
}
Inside my fragment
override fun onItemRemoveClick(position: Int) {
val currentList = recyclerAdapter.currentList.toMutableList()
currentList.removeAt(position)
recyclerAdapter.submitList(currentList)
}
Everythings works fine but mine delete from the bottom of the list instead of the current postion. What could be the problem?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With