问题
I'm using two adapters for the same list but each is differently sorted.
This is the adapterONE
(I removed almost everything non necessary for this question):
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)
}
Now afer calling the hide
function I want the same item to be removed in the second adapter so I tried:
videolist.removeAt(ppp)
notifyItemRemoved(ppp)
MainActivity().adapterTWO.hide(id) // this is what I added
And get the error:
lateinit property adapterTWO has not been initialized
But this isn't true because adapterTWO
has loaded the content
Please help and thanks in advance!
EDIT:
This is how I create the adapters in 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)
}
回答1:
I think you're unwillingly creating new MainActivity (in the added code you're calling its constructor). It'd also help if you posted some of MainActivity code
来源:https://stackoverflow.com/questions/54847334/android-recyclerview-call-method-function-from-second-adapter-kotlin