First time, If I add the item(click the send button) on the recyclerview, it does successfully,
but if I add the item second time, I expect see the item 1,2 but 1,2,1,2 add to the recyclerview
I'm using the multiViewType RecyclerView and the viewmodel
and I also use the databinding on the adapter code
Thank you for your help
below it's my code
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 {
}
}
}
private val _postChatResponse: MutableLiveData<Response<String>> = MutableLiveData() val postChatResponse: LiveData<Response<String>> get() = _postChatResponse fun postChat(hashMap: HashMap<String, Any>) { viewModelScope.launch { try { val response = chatRepository.postChat(hashMap) _postChatResponse.value = response } catch (e: Exception) { Log.d("postChatError", e.toString()) } } }