如何从Item <viewholder>()类刷新活动?

时间:2018-12-28 19:12:22

标签: android kotlin

如何从Item()类刷新活动。 我不知道这应该如何工作,或者甚至在那种班上也行不通。我知道如何在AppCompatActivity()类中执行此操作,但是假设这些命令无法正常工作。

那是我的物品:

class TrackItem(val track: Track): Item<ViewHolder>() {
override fun bind(viewHolder: ViewHolder, position: Int) {
    viewHolder.itemView.TrackName_txt.text = track.title
    viewHolder.itemView.TrackArtist_txt.text = track.artist
    viewHolder.itemView.TrackDuration_txt.text = track.duration
    Picasso.get().load(track.imageUrl).into(viewHolder.itemView.TrackImage_View)


    viewHolder.itemView.TrackDelete_btn.setOnClickListener {

        val playlistname = track.playlistId
        val uid = FirebaseAuth.getInstance().uid
        val FileId = track.FileId
        val databaseref = FirebaseDatabase.getInstance().getReference("/playlist/$uid/$playlistname/music/$FileId")
        databaseref.removeValue()
        val mp3ref = FirebaseStorage.getInstance().getReferenceFromUrl(track.trackUrl)
        mp3ref.delete()
        val coverref = FirebaseStorage.getInstance().getReferenceFromUrl(track.imageUrl)
        coverref.delete()

        recreate()


    }
}

override fun getLayout(): Int {
    return R.layout.trackinfo
}
}

1 个答案:

答案 0 :(得分:0)

如果您需要在活动中运行一些代码,这些代码可以用您的UI或数据进行重新加载/刷新/获取/删除等操作,只需创建并提供专门的界面即可。下面是一个示例。

class MyAdapter constructor(private val list: List<DataModel>, private val listener: UpdateActivityListener) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {

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

    override fun getItemCount(): Int = list.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.itemView.title.text = list[position].title
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        init {
            // Example of listener for your actions inside item
            view.setOnClickListener {
                listener.eventFirst()
            }
            view.setOnLongClickListener {
                listener.eventSecond(adapterPosition)
                true
            }
        }
    }

    // Example of callbacks which activity wait
    interface UpdateActivityListener {
        fun eventFirst()
        fun eventSecond(position: Int)
    }

}

我还看到您正在使用FastAdapter之类的库,只需重构代码并将侦听器设置为onBind方法即可。但是最好在ViewHolder init上做。