第一次,如果我添加项目(点击发送按钮)上的recyclerview,它成功,
但如果我第二次添加该项目,我希望看到项目1、2,但1、2、1、2添加到回收视图中
我使用的是multiViewType循环视图和视图模型
我还在适配器代码上使用数据绑定
谢谢你的帮忙
下面是我的代码
private val commentList = mutableListOf<Comment>()
private var chatAdpater = ChatAdapter()
....
binding.sendBtn.setOnClickListener {
postChat()
}
.....
private fun postChat(){
chatViewModel.postReChatResponse.observe(viewLifecycleOwner) {
val newCommentList = mutableListOf<Comment>()
commentList.add(
Comment(
nickname,
description,
writeTime,
boardId.toInt(),
categoryId.toInt(),
id,
images,
2,
commentsid.toInt(),
0,
null
)
)
newCommentList.addAll(commentList)
chatAdpater.setData(newCommentList,commentList.size-1)
}
}
---------adapter-------
.....
var commentList:MutableList<Comment>? = mutableListOf()
.....
@SuppressLint("NotifyDataSetChanged")
fun setData(commentList: MutableList<Comment>,position: Int){
this.commentList = commentList
notifyItemInserted(position)
}
class ViewHolder(val binding: ChatItemListBinding) :
RecyclerView.ViewHolder(binding.root) {
fun onBind(data: Comment) {
binding.comment = data
}
}
class ReViewHolder(val bindingTwo: ReChatItemListBinding) :
RecyclerView.ViewHolder(bindingTwo.root) {
fun onBind(data: Comment) {
bindingTwo.reComment = data
}
}
override fun getItemViewType(position: Int): Int {
return when (commentList!![position].isrecomment) {
1 -> 1
else -> 2
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val binding =
ChatItemListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
val bindingRe =
ReChatItemListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return when (viewType) {
1 -> ReViewHolder(bindingRe)
else -> ViewHolder(binding)
}
}
override fun getItemCount(): Int{
return commentList?.size ?: 0
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (commentList?.get(position)?.isrecomment) {
1 -> (holder as ReViewHolder).apply {
holder.onBind(commentList!![position])
}
2 -> (holder as ViewHolder).apply {
holder.onBind(commentList!![position])
holder.binding.chatText.setOnClickListener {
}
}
}
1条答案
按热度按时间8hhllhi21#
做一件事,只是使用单一的评论列表,并添加值到列表,然后使用notifyDataSetChanged适配器.这将工作.在这里,你添加值到列表一次又一次,所以这就是为什么它是重复的数据.