본문 바로가기
개발

(안드로이드 코틀린) 리사이클러 뷰어로 아이템 추가하기

by kks950115 2024. 1. 23.
728x90

이전 게시글에서 채팅창을 리사이클러뷰와 뷰홀더로 구현해보았다. 채팅도 써봐야할 것 아닌가? 

 

아래 링크는 이전 글이다.

 

https://kks950115.tistory.com/67

 


class ChatLogAdapter(var chatchatItems:MutableList<ChatLog>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private var chatItems = chatchatItems
   
	//....

    override fun getItemViewType(position: Int): Int {
        return chatItems[position].viewType
    }

    fun addItems (list:ChatLog){  // 데이터를 부분적으로 더하는 로직이다.
        chatItems.add(list)
        this.notifyItemInserted(chatItems.size)
    }
}

 

 

class ChatDetailActivity : AppCompatActivity() {

    private lateinit var binding : ActivityChatDetailBinding
    private var chatDetail : ChatDetail? = null
    private var chatLog : MutableList<ChatLog>? = null
    private var itemIndex :Int? = null

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityChatDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val bundle = intent.getBundleExtra("data")
        chatDetail = bundle?.getParcelable("chatDetail",ChatDetail::class.java)
        chatLog = bundle?.getParcelableArrayList("chatLog",ChatLog::class.java)
      
     	//.....

        binding.ivSendMsg.setOnClickListener {
            if(binding.etChatDetailInput.text.isNotEmpty()) sendMessage()
        }

    }


    private fun sendMessage(){
        val text = binding.etChatDetailInput.text.toString()
        var current = LocalDateTime.now()
        val formatter = DateTimeFormatter.ofPattern("a h:mm", Locale.KOREA) //
        val formatted = current.format(formatter)
        val data= ChatLog(text,formatted,2,R.drawable.background)
        Data.chatLogs[itemIndex!!].add(data) //더미데이터에 추가한다.
        (binding.rvChatDetailChatiing.adapter as ChatLogAdapter).addItems(data)  //어댑터의 additems를 사용해 어댑터에서도 더해준다. 
        binding.rvChatDetailChatiing.scrollToPosition(chatLog!!.size-1)//스크롤을 맨 아래로 내린다.
        binding.etChatDetailInput.text.clear()
    }
}

 

 

처음에 notifydatasetchanged() 가 안먹혀서 고생했는데 왜 안먹히나 했더니 어댑터에서 리스트에 들어갈 데이터를 수정하지 않았기 때문이였다. activity에서 백날 데이터 notifydatasetchanged()을 하여 새로 고침을 해도 데이터가 바뀌지 않았기 때문에 작동하지 않은 것이였다. 삭제도 위 과정과 크게 다르지 않다고 한다.

728x90
반응형

댓글