如何从适配器外部访问Recyclerview.ViewHolder参数?

时间:2018-07-23 13:16:50

标签: android android-recyclerview kotlin android-viewholder

我在SnapHelper上附加了recyclerview。然后,我为recyclerview制作了scrollListener,并且每次将该项目捕捉到显示的中心时,我都会找到该捕捉的视图,然后通过finViewHolderForAdapterPosition()获得其viewHolder实例。现在,我要访问的是在ViewHolder中创建的自定义变量。有什么办法可以访问它吗?基本上,此变量是在onBindViewHolder()中设置的,它包含自定义对象,其统计信息显示在此快照视图中。因此,我想从该视图中提取该json对象。

//inside onBindViewHolder()
holder.addressEntity = it

我已经尝试过了,但是没有检测到该变量。只能访问itemView(在构造函数中作为参数发送的变量)。

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作为内部类:

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)
}

1 个答案:

答案 0 :(得分:3)

您只需要将所有者转换为自己的所有者,所以

val myHolder = (searchedHolder as ViewHolder)
//Access custom info with variable