Created
April 24, 2020 18:10
-
-
Save oscarg798/9d617fbaa9a591ac20a4bd0d37afd47b to your computer and use it in GitHub Desktop.
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 ProductAdapter( | |
private val products: ArrayList<ViewProduct> | |
) : RecyclerView.Adapter<ProductViewHolder>() { | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder { | |
return ProductViewHolder( | |
LayoutInflater.from(parent.context).inflate(R.layout.product_item, parent, false) | |
) | |
} | |
override fun getItemCount(): Int = products.size | |
override fun onBindViewHolder(holder: ProductViewHolder, position: Int) { | |
holder.bind(products[position]) | |
} | |
override fun onBindViewHolder( | |
holder: ProductViewHolder, | |
position: Int, | |
payloads: MutableList<Any> | |
) { | |
if (payloads.isEmpty()) { | |
onBindViewHolder(holder, position) | |
} else { | |
for (data in payloads) { | |
when (data as Int) { | |
INVALID_PRODUCT_POSITION -> holder.updateProductQuantity(products[position].quantityInCart) | |
} | |
} | |
} | |
} | |
fun updateProducts(products: List<ViewProduct>) { | |
val result = DiffUtil.calculateDiff(ProductDiffUtilCallback(this.products, products)) | |
result.dispatchUpdatesTo(this) | |
this.products.clear() | |
this.products.addAll(products) | |
} | |
fun removeProduct(product: ViewProduct) { | |
val index = products.indexOf(product) | |
if (index == INVALID_PRODUCT_POSITION) { | |
return | |
} | |
products.removeAt(index) | |
notifyItemRemoved(index) | |
} | |
companion object { | |
private const val INVALID_PRODUCT_POSITION = 1 | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment