2

I have recyclerview attached to SnapHelper. Then I made scrollListener for recyclerview and everytime the item is snapped to the center of the display, I will find that snapped view, then I will get its viewHolder instance by finViewHolderForAdapterPosition(). Now what I want is to access custom variable created inside ViewHolder. Is there any way to access it? Basically this variable is set in onBindViewHolder() and it's containing custom object which stats are shown in this snapped view. So I want to extract that json object from that view.

//inside onBindViewHolder()
holder.addressEntity = it

I've tried this, but this variable is not detected. Only itemView (variable sent in constructor as parameter) is accessible.

addressRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
            if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                val centerView = snapHelper.findSnapView(addressRecyclerView.layoutManager)
                centerView!!.setBackgroundResource(R.drawable.payment_button_active)
                lastSnappedView = centerView
                val childViewHolder: RecyclerView.ViewHolder = recyclerView!!.findViewHolderForAdapterPosition(viewManager.getPosition(centerView))
                val selectedViewAddress: Address = childViewHolder.addressEntity //this doesnt work -- selectedViewAddress is red
                AndroidAssets.getInstance(context!!).deliveryAddress = selectedViewAddress 

            } else if (lastSnappedView != null){
                lastSnappedView!!.setBackgroundResource(R.drawable.payment_button_inactive)
                lastSnappedView = null
            }
        }
    })

ViewHolder inside adapter as inner class:

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

    //address item views
    var addressEntity: Address? = null
    val cityName: TextView = itemView.findViewById(R.id.cityName)
    val streetName: TextView = itemView.findViewById(R.id.streetName)
    val addressIcon: ImageView = itemView.findViewById(R.id.addressIcon)
}
martin1337
  • 2,384
  • 6
  • 38
  • 85
  • The ViewHolder might returns null value as the layout may not ready yet. If you have the position of the ViewHolder, would it be better, if you have a reference to a collection of data that you passed in the adapter earlier, to retrieve that item in the collection based on the position in adapter? – hjchin Jul 23 '18 at 13:36

1 Answers1

5

You just need to cast the holder as your own, so

val myHolder = (searchedHolder as ViewHolder)
//Access custom info with variable
Nick Mowen
  • 2,572
  • 2
  • 22
  • 38