如何在RecyclerView中获得物品的位置 [英] How to get position of the item in RecyclerView

查看:59
本文介绍了如何在RecyclerView中获得物品的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android开发人员的新手.在我的代码中,我没有使用onClick方法,但是我使用了setOnClickListener和Callback.主要的问题是我不知道如何在RecyclerView中获得物品的位置.

I'm new in Android dev. In my code i don't using onClick method, but i using setOnClickListener and Callback. The main problem that is in this way i don't know how to get the position of the item in RecyclerView.

这是我的适配器:

class TestAdapter(val test : ArrayList<Test>, private val testAdapterCallback: (Test, Int)->Unit) : RecyclerView.Adapter<TestAdapter.ViewHolder>(){

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        val v = LayoutInflater.from(parent.context).inflate(R.layout.test_view_item, parent, false)


        return ViewHolder(v)
    }

    override fun getItemCount(): Int {
        return test.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val num : Test = test[position]
        holder.textView.text = num.id.toString()
        holder.cardView.setTag(position)
        holder.cardView.setOnClickListener(){
            testAdapterCallback(num)
        }
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){

        val cardView = itemView.findViewById<CardView>(R.id.testCardView)
        val textView = itemView.findViewById<TextView>(R.id.testTextView)

    }

}

我已经在回调函数中添加了第二个参数,但是我不知道在这种和平的代码中如何更改适配器的初始化:

I have added second parametr into callback but i don't know how i must change my adapter's inicializations in this peace of code:

val adapter = TestAdapter(list) { item ->
                testAdapterItemClick(item)
            }

在活动中,我正在使用这种方法:

In activity i'm using this method :

private fun testAdapterItemClick(item: Test) {}

请帮助我检查所选元素的位置.以后再用提前谢谢)

Please, help me to check the position of the choosen element. I need it later. Thanks in advance)

P.S.对不起,我的英语

P.S. Sorry for my English

推荐答案

将位置添加为回调中的参数.

Add the position as parameter in the callback.

因此,而不是: priv val testAdapterCallback:(Test)-> Unit

使用:私有val testAdapterCallback :(测试,内部)->单元.

这样,您可以在回调函数中传递位置.

This way you can pass the position in the callback.

holder.cardView.setOnClickListener(){
    testAdapterCallback(num, position)
}

在您的活动中:

val adapter = TestAdapter(list) { item, position ->
                testAdapterItemClick(item)
            }

这篇关于如何在RecyclerView中获得物品的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆