gpt4 book ai didi

android - 封装ViewHolder功能以供重用

转载 作者:行者123 更新时间:2023-12-02 17:51:39 24 4
gpt4 key购买 nike

我有一个带有新闻提要的应用程序。我正在使用回收器 View 来填充我的新闻源。我有 10 种不同的回收者 View View 持有者,具体取决于从服务器接收的内容类型。一切都很好。

我的问题是,当用户单击回收器 View 中的项目时,用户会被带到一个新 fragment ,其中包含下面的内容和所有评论。

我的问题是这是一个新 fragment ,所以我位于回收器 View 之外。在这种情况下,我必须膨胀回收器 View 中单击的项目的布局,这很好。但是,它应该具有提要中的项目的所有功能,例如播放媒体(视频、音频)、导航到新 fragment 。

我的问题是,是否有可能以某种方式将viewholder的功能封装在recyclerview中?否则将重复相同的功能。

感谢任何帮助。 enter image description here

我附上了一张图来帮助说明。

最佳答案

class VideoViewHolder(
private binding: VideoItemBinding
) : RecyclerView.ViewHolder(binding.root){

companion object {
fun create(
inflater: LayoutInflater,
viewGroup: ViewGroup
): VideoViewHolder {
val binding = DataBindingUtil.inflate<VideoItemBinding>(
inflater, R.layout.item_video, viewGroup, false
)
return VideoViewHolder(binding)
}
}


fun bind(video: Video){
// bind view to video model
// set click listeners
// fire network request on click events and on response check if the viewholder is binded to same model else its has been reused.

}
}

来自视频适配器

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return VideoViewHolder.create(inflater, parent)

}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

when (holder) {
is VideoViewHolder -> {
holder.bind(item as Video, doubtsRepo)
}
}
}

要在没有适配器的情况下在 Activity/fragment/容器布局中重用,请手动创建 View 持有者并调用其绑定(bind)函数

val vh = VideoViewHolder.create(inflater, parent) 
// get view from vh.binding.root and manually add it to view container and then bind the model to the view to reuse view holder functionality without any changes.
vh.bind(video)

关于android - 封装ViewHolder功能以供重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34267937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com