From 508dff3bae737d5c340606206829c39a0ca60889 Mon Sep 17 00:00:00 2001 From: "kehaoyuan@ghzhushou.com" Date: Mon, 9 Mar 2020 15:08:03 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=9D=E8=AF=95=E4=BF=AE=E5=A4=8D=E6=B8=B8?= =?UTF-8?q?=E6=88=8F=E5=BA=93=E9=97=AA=E5=B1=8F=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../GameHorizontalItemViewHolder.kt | 32 +++++++++++-------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/com/gh/gamecenter/game/horizontal/GameHorizontalItemViewHolder.kt b/app/src/main/java/com/gh/gamecenter/game/horizontal/GameHorizontalItemViewHolder.kt index 4b5da091fa..f1b9b1c513 100644 --- a/app/src/main/java/com/gh/gamecenter/game/horizontal/GameHorizontalItemViewHolder.kt +++ b/app/src/main/java/com/gh/gamecenter/game/horizontal/GameHorizontalItemViewHolder.kt @@ -2,6 +2,7 @@ package com.gh.gamecenter.game.horizontal import android.text.TextUtils import android.view.Gravity +import android.view.ViewTreeObserver import android.widget.TextView import androidx.databinding.BindingAdapter import com.gh.base.BaseRecyclerViewHolder @@ -15,27 +16,30 @@ class GameHorizontalItemViewHolder(val binding: GameHorizontalItemBinding) : Bas @BindingAdapter("setHorizontalNameAndGravity") fun setHorizontalNameAndGravity(view: TextView, name: String?) { view.text = name - view.post { - view.gravity = if (view.lineCount >= 2) { - Gravity.START - } else { - Gravity.CENTER + view.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener{ + override fun onGlobalLayout() { + view.viewTreeObserver.removeOnGlobalLayoutListener(this); + view.gravity = if (view.lineCount >= 2) { + Gravity.START + } else { + Gravity.CENTER + } + val newText = autoSplitText(view); + if (!TextUtils.isEmpty(newText)) { + view.text = newText; + } } - - val newText = autoSplitText(view) - if (!TextUtils.isEmpty(newText)) { - view.text = newText - } - view.requestLayout() - } + }) } // 手动把文本进行换行处理 - private fun autoSplitText(tv: TextView): String { + private fun autoSplitText(tv: TextView): String? { try { val rawText = tv.text.toString() val tvPaint = tv.paint - val tvWidth = (tv.width - tv.paddingLeft - tv.paddingRight).toFloat() + val width = tv.width + if (width == 0) return null // 为零时,执行以下代码会进入死循环 + val tvWidth = (width - tv.paddingLeft - tv.paddingRight).toFloat() val rawTextLines = rawText .replace("\r".toRegex(), "") .split("\n".toRegex())