简体   繁体   中英

Get clicked item in recyclerview adapter

I want to create an android app with Kotlin. In this app, i use swagger also to get all the web service in a file. I want to create an interface, the description is as follows:

A RecyclerView horizontal that contains all the list of categories comes from a web service apiMobileProductCategoriesGetAllPost . after that, when i click on a which category, a RecyclerView(Grid) appear that contains all the product by category id.

I want to know how can i get the category id when i click on item,and how to use it in the activity The following the RecyclerView category adapter:

 class CategoryAdapter(private val categories: Array<ProductCategoryData>) :
    RecyclerView.Adapter<CategoryAdapter.ViewHolder>(), View.OnClickListener {

    private var onItemClickListener: OnItemClickListener? = null

    override fun onClick(v: View?) {
        if (v != null) {
            onItemClickListener?.onItemClick(v, ProductCategoryData())
        }
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        this.onItemClickListener = onItemClickListener
    }

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

    override fun getItemCount() = categories.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val itemCategory: ProductCategoryData = categories[position]

        holder.categoryId.text = itemCategory.id.toString()

        println(holder.categoryId.text)
        println(itemCategory.name?.get("En").toString())
        holder.categoryName.text = itemCategory.name?.get("En").toString()
        println(itemCategory.id)
        if (itemCategory.logo != null) {
            Picasso.get()
                .load("..../T/${itemCategory.logo}")
                .into(holder.categoryImage, object : com.squareup.picasso.Callback {
                    override fun onError(e: Exception?) {
                        holder.categoryImage.setImageResource(R.drawable.homecraftdefault)
                    }

                    override fun onSuccess() {
                        Picasso.get().load("....T/${itemCategory.logo}")
                            .into(holder.categoryImage)
                    }

                })
            holder.itemView.setOnClickListener {
                onItemClickListener?.onItemClick(holder.itemView,itemCategory)
            }
        }
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
        val categoryName: TextView = itemView.categoryName
        val categoryImage: ImageView = itemView.categoryImage
        val categoryId: TextView = itemView.categoryId
        override fun onClick(v: View?) {
            if (v != null) {
                onItemClickListener?.onItemClick(v, ProductCategoryData())
            }
        }

    }

    interface OnItemClickListener {
        fun onItemClick(view : View, viewModel:ProductCategoryData)
    }

}

The following code is relative to the activity:

class CategoryByProduct : AppCompatActivity(), CategoryAdapter.OnItemClickListener {

    override fun onItemClick(view: View, viewModel: ProductCategoryData) {
        var params =  "CategoryProductID";"5cc057458c4d9823743736d2"
        println(viewModel.id)
        val products = mobileApi!!.apiMobileProductsGetAllPost(params, 0, 50, "", "")
        recyclerViewProductByCategory.apply {
            recyclerViewProductByCategory.layoutManager = GridLayoutManager(this@CategoryByProduct, 2)
            recyclerViewProductByCategory.adapter = ProductAdapter(products)
        }    }

    var mobileApi: MobileApi? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.list_product_by_category)
        mobileApi = MobileApi()
        val params = HashMap<String, String>()
        GlobalScope.launch(Dispatchers.IO) {

            val categories = mobileApi!!.apiMobileProductCategoriesGetAllPost(params, 0, 50, "", "")
            withContext(Dispatchers.Main) {
                recyclerViewCategories.apply {
                    recyclerViewCategories.layoutManager =
                        LinearLayoutManager(this@CategoryByProduct, OrientationHelper.HORIZONTAL, false)
                    recyclerViewCategories.adapter = CategoryAdapter(categories)
                }
            }
        }



    }


    }

您可以通过调用adapterPosition来获得该类别在视图支架中的位置,并由此可以从您提供给构造函数中的适配器的列表中获得该类别(categories [adapterPosition])

In your case it is very simple.Try these:-

holder.tv_broadcast_title.text=broadList[position].name

where broadlist is my array list created in the adapter itself.In this list the json data is getting stored from api.

internal var broadList = ArrayList<Model>()

and .name is the name of key to fetch name from json data.

holder.categoryName.text = itemCategory.name?.get("En").toString()

in your case do something like this:-

itemCategory[position].name

First of all , never put your onclick in onBindViewHolder That's not a good practice, after that i think you need to get the ID of the category i will give you simple example in all of the Adapter Class

class NewsAdapter (val context: Context, private val arrayList: ArrayList <NewsModel>):
RecyclerView.Adapter <NewsAdapter.Holder> () {

companion object {
   // val TAG: String = OperationAdapter::class.java.simpleName
}

override fun onCreateViewHolder (parent: ViewGroup, viewType: Int): Holder {
    return Holder (LayoutInflater.from (parent.context ).inflate (R.layout.newslist , parent, false))
}

override fun getItemCount (): Int = arrayList. size

override fun onBindViewHolder (holder: Holder, position: Int) {

    val mynews = arrayList[position]
    holder.setData(mynews , position)

}

inner class Holder (itemView: View): RecyclerView.ViewHolder (itemView) {
    private var currentnews: NewsModel? = null
    private var currentPosition: Int = 0


    init {
        //The click listener

        itemView.newscardview.setOnClickListener {

            //do it here
            Toast.makeText(this,currentnews!!.id,Toast.LENGTH_SHORT).show()

        }
        //the end of the init
    }

    //getting data from model and bind it into View
    fun setData(news: NewsModel?, position: Int) {
        news?.let {
            itemView.newsid.text = news.id
            itemView.newstitle.text = news.title
            itemView.body.text = news.body
            itemView.txtdate.text = news.ndate

        }

        this.currentnews = news
        this.currentPosition = position
        }
      }

   }

In this example you will get the news ID when you click newscardview , i hope to understand it

In your Activity

put this code in onCreate

//set up the recycleview
mRecyclerView.setHasFixedSize (true)
mRecyclerView. layoutManager = LinearLayoutManager(this)

mRecyclerView is my RecycleView

also call your Adapter class in anywhere you want

//adapter
      val adapter = NewsAdapter (this,arrayList)
                    adapter.notifyDataSetChanged()
                    mRecyclerView.adapter = adapter

To get data from adapter to activity, you can make an interface in the adapter or globally and from the activity you can pass that interface in adapter's constructor and use that to get data. I am giving you an example.

interface ProductCategoryListner {
        fun getProductCategory(viewModel:ProductCategoryData)
    }

Not in adapter's constructor add this interface.

class CategoryAdapter(private val categories: Array<ProductCategoryData>,private val productCategoryListner: ProductCategoryListner):
    RecyclerView.Adapter<CategoryAdapter.ViewHolder>(), View.OnClickListener {

Now you can use this to pass data in the activity when you click on view.

productCategoryListner.getProductCategory(categories[adapterPosition])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM