android - 正确使用 TextUtils.commaEllipsize

标签 android android-layout textutils

我正在寻找一些关于如何通过 TextView 正确使用它的示例代码。

我在 Google 搜索中唯一找到的是这个 test unit for the TextUtils class .

一些指导将不胜感激。

编辑:

我查看了我在这里得到的答案,并尝试在我的代码中实现它。我使用了这个代码 fragment :

    TextView title = (TextView) view.findViewById(R.id.listitemThreadsTitle);
    title.setVisibility(View.VISIBLE);

    TextPaint p = title.getPaint();
    String strTitle = "Moe, Joe, Isaac, Bethany, Cornelius, Charlie";
    title.setText(strTitle);
    float avail = p.measureText(strTitle);
    CharSequence ch = TextUtils.commaEllipsize(strTitle, p, avail, "one more", "%d more");
    title.setText(ch);

但结果绝对不是它应该是的。

更像是:Moe、Joe、Isaac、Betha...

代替:Moe、Joe、Isaac + 3

最佳答案

public static CharSequence commaEllipsize (CharSequence text, TextPaint p, 
                                       float avail, String oneMore, String more)

参数:

text - 要截断的文本
p - 用来测量文本的 Paint
avail - 文本可用的水平宽度
oneMore - 当前语言环境中“1 more”的字符串
more - 当前语言环境中“%d more”的字符串

示例用法:

String text = "Apple, Orange, Mango, Banana";
TextView tv = new TextView(context);
float textWidth = tv.getPaint().measureText(text );
String tempStr = TextUtils.commaEllipsize(text, tv.getPaint(), textWidth, 
                                           "1 more", "%d more");
tv.setText(tempStr);

更新:

TextView title = (TextView) view.findViewById(R.id.listitemThreadsTitle);
title.setVisibility(View.VISIBLE);

TextPaint p = title.getPaint();
String strTitle = "Moe, Joe, Isaac, Bethany, Cornelius, Charlie";
title.setText(strTitle);
float avail = title.getMeasuredWidth();
CharSequence ch = TextUtils.commaEllipsize(strTitle, p, avail, "one more", "%d more");
title.setText(ch);

关于android - 正确使用 TextUtils.commaEllipsize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13518450/

相关文章:

android - 在 ConstraintLayout 中等距分布 View

android - 如何在 Android 中设计此 UI?

java - 检查空文本编辑

android - 开始使用 Android 电子市场?

android - 如何保护包含 NDEF 消息的 Mifare Classic 标签?

android - 以编程方式添加 View 时不显示 TextInputLayout

android - Kotlin:isNullOrEmpty 与 TextUtils.isEmpty

java - 将数据推送到设备的最佳方式是什么?

android - 如何设计单选对话框?