Textview的maxLines大于1行时,"android:ellipsize="end" 省略号失效
16lz
2021-12-30
Textview的maxLines大于1行时,"android:ellipsize="end" 省略号失效,这个问题一直都存在,我查找了很多博客,结合自己的实战经验做出分享,希望帮助更多的同仁们。详细如下:
第一步:在布局文件中加上这两个属性 android:ellipsize="end" 和 android:maxLines="2",假设最多不超过2行.。
第二步:写一个工具类。
package com.kqt.live.commom;import android.annotation.SuppressLint;import android.os.Build;import android.view.ViewTreeObserver;import android.widget.TextView;/** * Created with Android Studio. * User: huanggh * Date: 2020/4/23 * Time: 15:20 * Desc: maxLine超过1行时,省略号失效问题解决方案 */public class TextViewUtil { /** * 参数:maxLines 要限制的最大行数 * 参数:content 指TextView中要显示的内容 */ public static void setMaxEcplise(final TextView mTextView, final int maxLines, final String content) { ViewTreeObserver observer = mTextView.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { mTextView.setText(content); if (mTextView.getLineCount() > maxLines) { int lineEndIndex = mTextView.getLayout().getLineEnd(maxLines - 1); //下面这句代码中:我在项目中用数字3发现效果不好,改成1了 String text = content.subSequence(0, lineEndIndex - 3) + "..."; mTextView.setText(text); } else { removeGlobalOnLayoutListener(mTextView.getViewTreeObserver(), this); } } }); } @SuppressWarnings("deprecation") @SuppressLint("NewApi") private static void removeGlobalOnLayoutListener(ViewTreeObserver obs, ViewTreeObserver.OnGlobalLayoutListener listener) { if (obs == null) return; if (Build.VERSION.SDK_INT < 16) { obs.removeGlobalOnLayoutListener(listener); } else { obs.removeOnGlobalLayoutListener(listener); } }}
第三步:在代码中使用。
大功告成,效果如下:
更多相关文章
- android中的ellipsize
- EditText(细节) android:maxLines="1"失效原因以及解决
- 近距离端详Android(安卓)ART运行时库
- android 学习知识点累计
- android maxLines ellipsize 配合使用失效,解决办法
- Android(安卓)M 新的运行时权限开发者需要知道的一切
- android:ellipsize="end" + android:maxLines="" 失败的原因与解
- Android(安卓)M 新的运行时权限开发者需要知道的一切
- Android(安卓)M 新的运行时权限开发者需要知道的一切