본문 바로가기
IT/Android

Kotlin] 안드로이드 채팅방 날짜 표시

by 깻잎쌈 2021. 5. 1.
반응형
 

How do I display the calendar date on the top of chat messages?

I am working on a chat application but I am struggling to figure out how to display the calendar date on the top of chat messages; for example, something like this: Another image with timestamps: ...

stackoverflow.com

각 채팅 메세지에 대한 Adapter에 해당 코드를 넣어준다.

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.bind(chatMsgList.get(position)!!, context)

            val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")

            // 전송 시간
            val msg : ChatMessage = chatMsgList[position]!!
            val msgDate = dateFormat.parse(msg.dateInsert)
            val msgTime = Timestamp(msgDate.time).time

            // 이전 메세지 전송 시간
            var previousMessageTime: Long = 0L
            if (position > 0) {
                val previousMsg: ChatMessage = chatMsgList[position - 1]!!
                val previousMsgDate = dateFormat.parse(previousMsg.dateInsert)
                previousMsgTime = Timestamp(previousMsgDate.time).time          
            }

            showDate(msgTime, previousMsgTime, holder.textDate, holder.layoutDate)
        }

 

// 시간 표시
private fun showDate(time1: Long, time2: Long, timeText: TextView?, layout: RelativeLayout?) {
            val cal1 = Calendar.getInstance()
            val cal2 = Calendar.getInstance()
            cal1.timeInMillis = time1
            cal2.timeInMillis = time2

            // 채팅방 첫 메세지면 날짜 표시 
            if (time2 == 0L) {       
                layout!!.visibility = View.VISIBLE
                timeText!!.text = "${cal1[Calendar.MONTH]+1}월 ${cal1[Calendar.DATE]}일"

            } else {
                val sameDate =
                    cal1[Calendar.YEAR] == cal2[Calendar.YEAR] && cal1[Calendar.MONTH] == cal2[Calendar.MONTH]
                            && cal1[Calendar.DATE] == cal2[Calendar.DATE]

                // 이전과 날짜가 다르면 날짜 표시
                if (!sameDate) {                
                    layout!!.visibility = View.VISIBLE
                    timeText!!.text = "${cal1[Calendar.MONTH]+1}월 ${cal1[Calendar.DATE]}일"
                }

            }
        }

 

반응형

댓글