仅椭圆化 TextView 中的一部分

发布于 2024-09-08 18:15:03 字数 213 浏览 5 评论 0原文

我想知道是否可以仅缩写 TextView 中字符串的一部分。我想做的是这样的:

Element with short title (X)
Element with a very lo...(X)

标题应该是省略号,但 X 必须始终可见。就我而言,不可能使用多个 TextView。您认为有一种简单的方法可以做到这一点吗?

谢谢!

I was wondering if it is possible to abbreviate only a portion of a string in a TextView. What I would like to do is something like this:

Element with short title (X)
Element with a very lo...(X)

The title should be ellipsized, but the X must be always visible. In my case, is not possible to use more than one TextView. Do you think there is a simple way of doing this?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

揽清风入怀 2024-09-15 18:15:03

我确实需要一个干净的项目解决方案,所以在四处寻找并没有找到任何我喜欢的解决方案后,我花了一些时间来写这篇文章。

这是具有增强省略号控制的 TextView 的实现。它的工作方式是使用 Android 的 Spanned 界面。它定义了一个枚举,您可以使用它来标记您希望在需要时省略的特定文本部分。

限制:

  • 中间不支持省略号。如果确实需要的话,这应该很容易添加(我没有)。
  • 此类始终将文本渲染到一行上,因为它仅支持单行文本。如果需要的话,欢迎其他人扩展它(但这是一个更难的问题)。

下面是一个用法示例:

FooActivity.java

class FooActivity extends Activity {

  /**
   * You can do this however you'd like, this example uses this simple
   * helper function to create a text span tagged for ellipsizing
   */
  CharSequence ellipsizeText(String text) {
    SpannableString s = new SpannableString(text);
    s.setSpan(TrimmedTextView.EllipsizeRange.ELLIPSIS_AT_END, 0, s.length(),
      Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    return s;
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.foo_layout);
    TextView textView = (TextView) findViewById(R.id.textView4);
    SpannableStringBuilder text = new SpannableStringBuilder();
    text.append(ellipsizeText("This is a long string of text which has important information "));
    text.append("AT THE END");
    textView.setText(text);
  }
}

res/layouts/foo_layout.xml

<com.example.text.TrimmedTextView
  android:id="@+id/textView4"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>

就是这样

下面是结果示例:

screenshot_of_example

实现

package com.example.text;

import android.content.Context;
import android.text.Editable;
import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;

public class TrimmedTextView extends TextView {
  public static enum EllipsizeRange {
    ELLIPSIS_AT_START, ELLIPSIS_AT_END;
  }

  private CharSequence originalText;
  private SpannableStringBuilder builder = new SpannableStringBuilder();

  /**
   * This allows the cached value of the original unmodified text to be
   * invalidated whenever set externally.
   */
  private final TextWatcher textCacheInvalidator = new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
      originalText = null;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
  };

  public TrimmedTextView(Context context) {
    this(context, null, 0);
  }

  public TrimmedTextView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public TrimmedTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    addTextChangedListener(textCacheInvalidator);
    Log.v("TEXT", "Set!");
  }

  /**
   * Make sure we return the original unmodified text value if it's been
   * custom-ellipsized by us.
   */
  public CharSequence getText() {
    if (originalText == null) {
      return super.getText();
    }
    return originalText;
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    Layout layout = getLayout();
    CharSequence text = layout.getText();
    if (text instanceof Spanned) {
      Spanned spanned = (Spanned) text;
      int ellipsisStart;
      int ellipsisEnd;
      TruncateAt where = null;
      ellipsisStart = spanned.getSpanStart(EllipsizeRange.ELLIPSIS_AT_START);
      if (ellipsisStart >= 0) {
        where = TruncateAt.START;
        ellipsisEnd = spanned.getSpanEnd(EllipsizeRange.ELLIPSIS_AT_START);
      } else {
        ellipsisStart = spanned.getSpanStart(EllipsizeRange.ELLIPSIS_AT_END);
        if (ellipsisStart >= 0) {
          where = TruncateAt.END;
          ellipsisEnd = spanned.getSpanEnd(EllipsizeRange.ELLIPSIS_AT_END);
        } else {
          // No EllipsisRange spans in this text
          return;
        }
      }

      Log.v("TEXT", "ellipsisStart: " + ellipsisStart);
      Log.v("TEXT", "ellipsisEnd:   " + ellipsisEnd);
      Log.v("TEXT", "where:         " + where);

      builder.clear();
      builder.append(text, 0, ellipsisStart).append(text, ellipsisEnd, text.length());
      float consumed = Layout.getDesiredWidth(builder, layout.getPaint());
      CharSequence ellipsisText = text.subSequence(ellipsisStart, ellipsisEnd);
      CharSequence ellipsizedText = TextUtils.ellipsize(ellipsisText, layout.getPaint(),
          layout.getWidth() - consumed, where);
      if (ellipsizedText.length() < ellipsisText.length()) {
        builder.clear();
        builder.append(text, 0, ellipsisStart).append(ellipsizedText)
            .append(text, ellipsisEnd, text.length());
        setText(builder);
        originalText = text;
        requestLayout();
        invalidate();
      }
    }
  }
}

I really needed a clean solution for a project so after searching around and not finding any solutions I felt I liked, I took some time to write this up.

Here is an implementation of a TextView with enhanced ellipsis control. The way it works is by using Android's Spanned interface. It defines an enum you can use to tag the specific section of text you'd like to be ellipsized if needed.

Limitations:

  • Does not support ellipsis at MIDDLE. This should be easy to add if it's really needed (I didn't).
  • This class will always render the text onto one line, as it only supports a single line of text. Others are welcome to extend it if that's needed (but it's a far harder problem).

Here's a sample of the usage:

FooActivity.java

class FooActivity extends Activity {

  /**
   * You can do this however you'd like, this example uses this simple
   * helper function to create a text span tagged for ellipsizing
   */
  CharSequence ellipsizeText(String text) {
    SpannableString s = new SpannableString(text);
    s.setSpan(TrimmedTextView.EllipsizeRange.ELLIPSIS_AT_END, 0, s.length(),
      Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    return s;
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.foo_layout);
    TextView textView = (TextView) findViewById(R.id.textView4);
    SpannableStringBuilder text = new SpannableStringBuilder();
    text.append(ellipsizeText("This is a long string of text which has important information "));
    text.append("AT THE END");
    textView.setText(text);
  }
}

res/layouts/foo_layout.xml

<com.example.text.TrimmedTextView
  android:id="@+id/textView4"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>

That's it

Here's an example of the result:

screenshot_of_example

The Implementation

package com.example.text;

import android.content.Context;
import android.text.Editable;
import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;

public class TrimmedTextView extends TextView {
  public static enum EllipsizeRange {
    ELLIPSIS_AT_START, ELLIPSIS_AT_END;
  }

  private CharSequence originalText;
  private SpannableStringBuilder builder = new SpannableStringBuilder();

  /**
   * This allows the cached value of the original unmodified text to be
   * invalidated whenever set externally.
   */
  private final TextWatcher textCacheInvalidator = new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
      originalText = null;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
  };

  public TrimmedTextView(Context context) {
    this(context, null, 0);
  }

  public TrimmedTextView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public TrimmedTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    addTextChangedListener(textCacheInvalidator);
    Log.v("TEXT", "Set!");
  }

  /**
   * Make sure we return the original unmodified text value if it's been
   * custom-ellipsized by us.
   */
  public CharSequence getText() {
    if (originalText == null) {
      return super.getText();
    }
    return originalText;
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    Layout layout = getLayout();
    CharSequence text = layout.getText();
    if (text instanceof Spanned) {
      Spanned spanned = (Spanned) text;
      int ellipsisStart;
      int ellipsisEnd;
      TruncateAt where = null;
      ellipsisStart = spanned.getSpanStart(EllipsizeRange.ELLIPSIS_AT_START);
      if (ellipsisStart >= 0) {
        where = TruncateAt.START;
        ellipsisEnd = spanned.getSpanEnd(EllipsizeRange.ELLIPSIS_AT_START);
      } else {
        ellipsisStart = spanned.getSpanStart(EllipsizeRange.ELLIPSIS_AT_END);
        if (ellipsisStart >= 0) {
          where = TruncateAt.END;
          ellipsisEnd = spanned.getSpanEnd(EllipsizeRange.ELLIPSIS_AT_END);
        } else {
          // No EllipsisRange spans in this text
          return;
        }
      }

      Log.v("TEXT", "ellipsisStart: " + ellipsisStart);
      Log.v("TEXT", "ellipsisEnd:   " + ellipsisEnd);
      Log.v("TEXT", "where:         " + where);

      builder.clear();
      builder.append(text, 0, ellipsisStart).append(text, ellipsisEnd, text.length());
      float consumed = Layout.getDesiredWidth(builder, layout.getPaint());
      CharSequence ellipsisText = text.subSequence(ellipsisStart, ellipsisEnd);
      CharSequence ellipsizedText = TextUtils.ellipsize(ellipsisText, layout.getPaint(),
          layout.getWidth() - consumed, where);
      if (ellipsizedText.length() < ellipsisText.length()) {
        builder.clear();
        builder.append(text, 0, ellipsisStart).append(ellipsizedText)
            .append(text, ellipsisEnd, text.length());
        setText(builder);
        originalText = text;
        requestLayout();
        invalidate();
      }
    }
  }
}
无戏配角 2024-09-15 18:15:03

你可以尝试使用这样的东西:

myTextView.setEllipsize(TextUtils.TruncateAt.MIDDLE);

它可能不会给你你想要的东西,但它可能会做这样的事情:

元素带有...标题 (X)

参考信息

TruncateAt
setEllipsize

You can try using something like this:

myTextView.setEllipsize(TextUtils.TruncateAt.MIDDLE);

It might not give you exactly what you want though, it may do something like this:

Element wi...title (X)

Reference Info

TruncateAt
setEllipsize

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文