Kotlin: Как щелкнуть по элементу в обзоре рециклера внутри другого обзора рециклера - PullRequest
1 голос
/ 20 января 2020

После просмотра всех похожих вопросов я не могу найти решение своей проблемы, описание которой следующее: В моем приложении android я использую Kotlin в качестве языка. В моем приложении у меня много категорий, и в каждой категории есть список товаров. В своей домашней деятельности я создаю вертикальный RecyclerView с именем "productListOfCategory". В адаптере «productListOfCategory» - текстовое представление для отображения названия категории и окно-ресивер для отображения списка всех связанных продуктов. Следующий код представляет собой описание адаптера «ProductListOfProductTypeAdapter»: (ProductType = category)

 class ProductListOfProductTypeAdapter(private val context: Context, private val ProductTypeIDWithProduct: Map<String, Array<ProductData>>, private val productTypeDetail: Array<ProductTypeData>)
    : RecyclerView.Adapter<ProductListOfProductTypeAdapter.ViewHolder>(),ProductOfProductTypeAdapter.OnItemClickListener{
    override fun onItemClick(view: View, viewModel: ProductData) {
        val intent = Intent(context,ProductDetail::class.java)
        context.startActivity(intent)
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_list_product_product_type, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount() = ProductTypeIDWithProduct.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val itemType = ProductTypeIDWithProduct.keys.elementAt(position)
        holder.productTypeName.text = getName(itemType)

        val arrayProductOfProductType = ProductTypeIDWithProduct[itemType] as ArrayList<ProductData>

        holder.productListOfProductType.apply {
            holder.productListOfProductType.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
            holder.productListOfProductType.adapter = ProductOfProductTypeAdapter(arrayProductOfProductType,context,this@ProductListOfProductTypeAdapter)
        }

    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val productTypeName: TextView = itemView.textViewProductTypeName
        val productListOfProductType: RecyclerView = itemView.recyclerViewProductOfProductType
    }

«ProductOfProductTypeAdapter» - это второй адаптер, код которого следующий:

class ProductOfProductTypeAdapter(private val products: ArrayList<ProductData>, private val context: Context,private val mListener: OnItemClickListener)
    : RecyclerView.Adapter<ProductOfProductTypeAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_product_featured, parent, false)
        return ViewHolder(view)

    }

    override fun getItemCount() = products.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val productItem = products[position] as Map<String, Map<String, String>>

        holder.productName.text = productItem["name"]?.get("En").toString()
        holder.productWeight.text = productItem["weight"].toString().plus(context.resources.getString(R.string.ml))
        holder.productPrice.text = "$".plus(productItem["price"].toString()).plus("/")
        holder.productRating.text = productItem["reviewsValue"].toString()
        holder.itemView.setOnClickListener {
            mListener.onItemClick(holder.itemView, products[position])
            notifyDataSetChanged()
        }
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val productName: TextView = itemView.itemProdFeaturedName
        val productPrice: TextView = itemView.itemProdFeaturedPrice
        val productImage: ImageView = itemView.itemProdFeaturedImage
        val productWeight: TextView = itemView.txtViewWeight
        val productRating: TextView = itemView.itemProdFeaturedRate
    }

   interface OnItemClickListener {
        fun onItemClick(view: View,viewModel: Map<String, Map<String, String>>)
    }

My Проблема в том, как щелкнуть продукт и отобразить сведения о продукте. Я пытаюсь выполнить следующее, но все еще не получаю желаемого.

1 Ответ

0 голосов
/ 20 января 2020

Разве ваш OnItemClickListener не должен выглядеть следующим образом?

interface OnItemClickListener {
    fun onItemClick(view: View, product: ProductData)
}

И вам нужно изменить способ запуска действия ProductDetail и указать свой идентификатор продукта или что-то еще, чтобы идентифицировать продукт, выбранный в дополнительном списке. данные о намерениях. Например:

val intent = Intent(context,ProductDetail::class.java)
intent.putExtra("PRODUCT_ID", product.id)
context.startActivity(intent)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...