Example in kotlin
sorry about my English
Try to make a click interface and use inside the Adadapter, with it you can take the position of the item
example ==> interface
interface MyInterface {
fun OnClickListener( string : String , position: Int, view: View)
}
How to use inside the adapter
class ProductAdadapter(
val context: Context,
private var myInterface : MyInterface
) : RecyclerView.Adapter<ProductAdadapter.ProductViewModel>() {
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ProductViewModel {
val view = LayoutInflater.from(context).inflate(R.layout.item_product_adapter, parent, false)
return ProductViewModel(view)
}
override fun getItemCount() = product.size
override fun getItemViewType(position: Int): Int {
return super.getItemViewType(position)
}
override fun onBindViewHolder(holder: ProductViewModel, position: Int) {
holder.bindView(product[position])
holder.mcvProductsAd.setOnClickListener{
myInterface .OnClickListener(product[position],position, it)
}
}
class ProductViewModel(item: View) : RecyclerView.ViewHolder(item) {
val mcvProductsAd = item.mcv_products_ad
fun bindView(product: Product) {
Glide.with(itemView.context).load(product.image).into(imageProduct)
}
}
}
afterwards and just make an implement inside the Fragment
class ProductFragment : Fragment(), MyInterface {
lateinit var productAdadapter: ProductAdadapter
companion object {
fun newInstance() = ProductFragment()
}
private lateinit var viewModel: ProductViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.product_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(ProductViewModel::class.java)
viewModel.loadMessages().observe(viewLifecycleOwner, androidx.lifecycle.Observer {
it?.let {
grid.layoutManager = GridLayoutManager(context!!, 2)
grid.adapter = ProductAdadapter(context!!, it, this)
}
})
mt_product_new.setOnClickListener { activity!!.onBackPressed() }
}
override fun OnClickListener(string: String, position: Int, view: View) {
Navigation.findNavController(it)
.navigate(R.id.action_my_orders_fragment_to_offers_fragment, null)
}
}
}