In Java/Kotlin, you pass by value, not by reference. When passing the list to the StaggeredProductCardRecyclerViewAdapter( theList )
, you should update the list from the Adapter, not the one you passed. Here's an example:
class StaggeredProductCardRecyclerViewAdapter(private val theList: List) { private var listOfItems = theList fun removeItem(position: Int) { listOfItems = listOfItems.remove(position) notifyDatasetChanged() } } val featured = view.findViewById(R.id.featured) as Button // set on-click listener featured.setOnClickListener { adapter.removeItem(1) }
EDIT:
You're operating on an immutable list inside the StaggeredProductCardRecyclerViewAdapter
. To filter items on the list based on "featured," for example, do this:
class StaggeredProductCardRecyclerViewAdapter(private val initList: List<ProductEntry>?) : RecyclerView.Adapter<StaggeredProductCardViewHolder>() { private var productList: List<ProductEntry>? = initList override fun getItemViewType(position: Int): Int { return position % 3 } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StaggeredProductCardViewHolder { var layoutId = R.layout.shr_staggered_product_card_first if (viewType == 1) { layoutId = R.layout.shr_staggered_product_card_second } else if (viewType == 2) { layoutId = R.layout.shr_staggered_product_card_third } val layoutView = LayoutInflater.from(parent.context).inflate(layoutId, parent, false) return StaggeredProductCardViewHolder(layoutView) } override fun onBindViewHolder(holder: StaggeredProductCardViewHolder, position: Int) { if (productList != null && position < productList.size) { val product = productList[position] holder.productTitle.text = product.title holder.productPrice.text = product.price ImageRequester.setImageFromUrl(holder.productImage, product.url) } } override fun getItemCount(): Int { return productList?.size ?: 0 } fun replaceList(items: List<ProductEntry>?) { productList = items notifyDatasetChanged() } }
And in ProductGridFragment
:
featured.setOnClickListener { adapter.replaceList(ProductEntry.initProductEntryList(resources, "featured")) }
Another approach: Refreshing Fragment's onCreateView method
supportFragmentManager.beginTransaction().detach(yourFragment).commitNow() supportFragmentManager.beginTransaction().attach(yourFragment).commitNow()
This will rerender the whole view. Use childFragmentManager
for different cases.
The most efficient solution when adapter data changes is to use notifyDatasetChanged()
.
Simple Way to Refresh
RecyclerView
in Fragment
viewpager.setAdapter(myViewPagerAdapter);
This will call the onResume()
method of the fragment.