package com.gh.gamecenter.common.view

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

/**
 * 去除省略号后面空白的TextView
 */
class NoEllipsizeSpaceTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    AppCompatTextView(context, attrs, defStyleAttr) {
    override fun setText(text: CharSequence?, type: BufferType?) {
        super.setText(text, type)
        post {
            if (layout != null) {
                val rawText = layout.text.toString()
                if (rawText.contains(ELLIPSIS_NORMAL) && rawText.contains(ELLIPSIS_BLANK)) {
                    val index = rawText.indexOf(ELLIPSIS_BLANK)
                    var trimText = rawText
                    if (index > 0) {
                        trimText = rawText.substring(0, index)
                    }
                    trimText = rawText.substring(0, trimText.length - 1) + ELLIPSIS_NORMAL
                    setText(trimText)
                }
            }
        }
    }

    companion object {
        private const val ELLIPSIS_NORMAL = "\u2026" // 省略号字符(...)
        private const val ELLIPSIS_BLANK = "\uFEFF" // 空白字符
    }
}