Skip to content Skip to sidebar Skip to footer

How To Get Position Of The Item In 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 posit

Solution 1:

Add the position as parameter in the callback.

So, instead of: private val testAdapterCallback: (Test)->Unit

Use: private val testAdapterCallback: (Test, Int)->Unit.

This way you can pass the position in the callback.

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

In your activity:

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

Solution 2:

Create interface for your OnClickListener

interfaceOnClickListener{
    funclickItem(test: Test, index: Int)
}

Pass listener to your adapter like below.

classTestAdapter(
        var test : ArrayList<Test>?,
        val clickListener: OnClickListener,
        var mActivity: Activity
    ) :
        RecyclerView.Adapter<TestAdapter.MyViewHolder>() {
}

Now in your onBindViewHolder add click listener.

var mtest= test !!.get(i)
    holder.cardView.setOnClickListener {
                clickListener.clickItem(mtest, i)
            }

Implement Listener to your activity and initialize it.

this.mOnClickListener = this

Pass listener to your adapter where you passing the arraylist.

mTestAdapter = TestAdapter(arrayList, mOnClickListener ,mActivity)

You'll get the position in your activity override method.

overridefuneditItem(mTest: Test, index: Int) {
        if (mTest!= null) {

        }
    }

Post a Comment for "How To Get Position Of The Item In Recyclerview"