如何判断Android TextView是否为单行并移除其右侧图标?
解决TextView单行时移除右侧图标的问题
需求:判断目标TextView是否为单行显示,若为单行则移除其右侧的drawableEnd图标。对应的布局代码如下:
<TextView android:id="@+id/newOrderMessageTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="12dp" android:background="@drawable/message_textview_background" android:drawableEnd="@drawable/angle_small_down" android:drawablePadding="10dp" android:ellipsize="end" android:padding="10dp" android:paddingStart="16dp" android:paddingEnd="16dp" android:text="" android:textStyle="bold" app:drawableStartCompat="@drawable/comment" />
实现方案
TextView没有直接提供判断行数的API,需要等布局完成后通过其Layout对象计算行数,再控制图标显示:
1. 监听布局完成事件
必须等TextView完成布局渲染,才能准确获取行数,因此需要借助ViewTreeObserver.OnGlobalLayoutListener监听布局完成。
2. 判断行数并调整图标
获取TextView的lineCount,若等于1则移除右侧图标,否则保留原图标。
Kotlin 实现代码
val textView = findViewById<TextView>(R.id.newOrderMessageTextView) textView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { // 移除监听,避免重复触发 textView.viewTreeObserver.removeOnGlobalLayoutListener(this) if (textView.lineCount == 1) { // 保留左侧图标,移除右侧图标 textView.setCompoundDrawablesRelativeWithIntrinsicBounds( textView.compoundDrawablesRelative[0], null, null, null ) } } })
Java 实现代码
TextView textView = findViewById(R.id.newOrderMessageTextView); textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // 移除监听 textView.getViewTreeObserver().removeOnGlobalLayoutListener(this); if (textView.getLineCount() == 1) { // 保留左侧图标,移除右侧图标 textView.setCompoundDrawablesRelativeWithIntrinsicBounds( textView.getCompoundDrawablesRelative()[0], null, null, null ); } } });
注意事项
- 若文本内容动态更新,需在
setText()后重新执行上述判断逻辑(比如重新添加监听或封装成单独方法调用)。 - 使用
setCompoundDrawablesRelativeWithIntrinsicBounds可适配RTL布局,确保图标位置符合语言方向。
内容的提问来源于stack exchange,提问作者Ömer Seyfettin Yavuzyiğit
相关产品推荐
相关产品推荐

