首页 > 解决方案 > Android recyclerview - 从第二个适配器调用方法/函数(Kotlin)

问题描述

我为同一个列表使用了两个适配器,但每个适配器的排序不同。

这是adapterONE(我删除了这个问题几乎所有不必要的东西):

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val video = videolist[position]

    holder.title.text = video.id.toString()

    holder.title.setOnClickListener {
        hide(video.id)
    }
}

override fun getItemCount() = videolist.size

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

class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!){
    val title = itemView!!.videoviewTitle!!
}


fun hide(id: Int){

    var ppp = 0

    for (i in 0 until videolist.size) {

        if(videolist[i].id == id){
            ppp = i
            break
        }
    }

    videolist.removeAt(ppp)
    notifyItemRemoved(ppp)
}

现在调用该hide函数后,我希望在第二个适配器中删除相同的项目,所以我尝试了:

videolist.removeAt(ppp)
notifyItemRemoved(ppp)
MainActivity().adapterTWO.hide(id) // this is what I added

并得到错误:

lateinit property adapterTWO has not been initialized

但这不是真的,因为adapterTWO已经加载了内容

请提前帮助和感谢!

编辑:

这就是我在 MainActivity 中创建适配器的方式

lateinit var adapter: RecentAdapter
lateinit var adapterTrending: TrendingAdapter

fun loadVids(endvids: MutableList<Videos>){

    adapter = RecentAdapter(this@MainActivity, endvids, isfavorites)

    recyclerViewRecent.adapter = adapter

    recyclerViewRecent.layoutManager = LinearLayoutManager(this@MainActivity)
    recyclerViewRecent.setHasFixedSize(true)

}


fun loadVidsRecent(endvids: MutableList<Videos>){

    adapterTrending = TrendingAdapter(this@MainActivity, endvids, isfavorites)

    recyclerViewTrending.adapter = adapterTrending

    recyclerViewTrending.layoutManager = LinearLayoutManager(this@MainActivity)
    recyclerViewTrending.setHasFixedSize(true)
}

标签: androidkotlinandroid-recyclerviewadapter

解决方案


我认为您不情愿地创建新的 MainActivity (在添加的代码中您正在调用其构造函数)。如果您发布一些 MainActivity 代码也会有所帮助


推荐阅读