【问题标题】:How to get the ellipsized text in a TextView如何在 TextView 中获取省略号的文本
【发布时间】:2012-06-14 22:01:11
【问题描述】:

如何将被 Android 截断的文本变成省略号?

我有一个文本视图:

<TextView
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:singleLine="true"
    android:text="Um longo texto aqui de exemplo" />

在设备上,这个 TextView 显示如下:

"Um longo texto a..."

我如何获得其余的文本?

我正在寻找类似getRestOfTruncate() 的东西,它会返回“qui de exemplo”。

【问题讨论】:

  • 我修正了您问题的标题和文字。我希望我有一个答案给你,但我不认为有办法做到这一点。这里的用例是什么?
  • 谢谢@AustynMahoney,可能应该做一些事情来完成它,否则,我会构建一些东西,问题是它会更困难,但如果我在这里发帖
  • 在 xml 布局中使用 android:text="@string/full_text",在需要时在 java 代码中使用 getString(R.string.full_text)

标签: java android textview truncate


【解决方案1】:
String text = (String) textView.getText().subSequence(textView.getLayout().getEllipsisStart(0), textView.getText().length());

【讨论】:

  • 工作完美,但我需要在 postRunnable 中插入您的代码,因为首先必须设计 textview,在完成时我这样做: new Handler().postDelayed(runnable with your code,1 milissegundo);
  • 这只有在我有android:singleLine="true" 时才有效。如果我将其设置为 false 并将 android:maxLines 设置为除 ` 之外的某个数字,则此方法总是返回整个文本,就好像它根本没有被省略一样。
【解决方案2】:

使用 textView.getLayout().getEllipsisStart(0) 仅在 android:singleLine="true" 时有效

如果设置了 android:maxLines,下面是一个可行的解决方案:

public static String getEllipsisText(TextView textView) {
    // test that we have a textview and it has text
    if (textView==null || TextUtils.isEmpty(textView.getText())) return null;
    Layout l = textView.getLayout();
    if (l!=null) {
        // find the last visible position
        int end = l.getLineEnd(textView.getMaxLines()-1);
        // get only the text after that position
        return textView.getText().toString().substring(end);
    }

    return null;
}

记住:这在视图已经可见之后才起作用。

用法:

textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            Log.i("test" ,"EllipsisText="+getEllipsisText(textView));
        }
    });

【讨论】:

    【解决方案3】:

    我的解决方案。 Kotlin 扩展功能:

    fun TextView.getEllipsizedText(): String {
    if (text.isNullOrEmpty()) return ""
    return layout?.let {
        val end = textContent.text.length - textContent.layout.getEllipsisCount(maxLines - 1)
        return text.toString().substring(0, end)
    } ?: ""
    }
    

    【讨论】:

    • 这不起作用,因为 EllipsisCount 只返回一行而不是整个文本!
    猜你喜欢
    • 2017-06-19
    • 2013-09-15
    • 2014-02-01
    • 2015-01-08
    • 2012-02-02
    • 1970-01-01
    • 2014-11-21
    • 2011-09-17
    • 2015-09-17
    相关资源
    最近更新 更多