Whatsapp Message Layout - How to get time-view in the same row

后端 未结 12 1064
执笔经年
执笔经年 2020-11-28 03:18

I was wondering how WhatsApp handles the time shown in every message.

For those who don\'t know:

  1. If the message is very short, the text and time are in
12条回答
  •  旧巷少年郎
    2020-11-28 04:08

    The previous answers didn't satisfy my needs as they were too complex and the scrolling on RecyclerView was way too slow! I could feel the stutter while scrolling. So, I modified @Rahul Shuklas answer to make it more efficient. I am sharing my result below. The code is self explanatory, I have added comments for more understandability.

    class ChatBubbleLayout : FrameLayout {
    constructor(context: Context) : super(context) {}
    
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
    
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}
    
    @TargetApi(21)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
    }
    
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    
        doMeasure()
    }
    
    private fun doMeasure() {
    
            val messageTextView = findViewById(R.id.tv_message)
            val dateTextView = findViewById(R.id.tv_message_time)
    
            // Message line count
            val lineCount = messageTextView.lineCount
    
            // Message padding
            val messageTextViewPadding = messageTextView.paddingLeft + messageTextView.paddingRight
    
            // First / Second last line of message
            val lastLineStart = messageTextView.layout.getLineStart(lineCount - 1)
            val lastLineEnd = messageTextView.layout.getLineEnd(lineCount - 1)
    
            // Width of First / Second last line of message
            var desiredWidth = Layout.getDesiredWidth(messageTextView.text.subSequence(lastLineStart,
                    lastLineEnd), messageTextView.paint).toInt()
    
            var desiredHeight = measuredHeight
    
            if (desiredWidth < minimumWidth && messageTextView.measuredWidth < minimumWidth) {
                // Probably a small or single line message
    
                desiredWidth = minimumWidth + messageTextViewPadding
    
            } else {
                // Probably a bit long or multiple line message
    
                desiredWidth = messageTextView.measuredWidth + messageTextViewPadding
            }
    
            if(desiredHeight < minimumHeight) {
                desiredHeight = minimumHeight
            }
    
            setMeasuredDimension(desiredWidth, desiredHeight)
        } 
    }
    

    My Layout XML file

    
    
        
    
            
    
            
    
        
    
    

    I hope it helps future readers.

提交回复
热议问题