Skip to content

Instantly share code, notes, and snippets.

@mrleolink
Created November 20, 2014 08:56
Show Gist options
  • Save mrleolink/d28326fdab07f877bfe6 to your computer and use it in GitHub Desktop.
Save mrleolink/d28326fdab07f877bfe6 to your computer and use it in GitHub Desktop.
A hack to set custom ellipsize and postfix string for Android's TextView
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomEllipsizeTextView">
<attr name="maxLines" format="integer" />
<attr name="postfix" format="reference" />
</declare-styleable>
</resources>
public class CustomEllipsizeTextView extends TextView {
private static final int MAX_LINE = 2;
private static final String ELLIPSIZE_STRING = "...";
private String originalText;
private int maxLines = MAX_LINE;
private String postfix;
private boolean postfixAdded;
public CustomEllipsizeTextView(Context context) {
this(context, null);
}
public CustomEllipsizeTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomEllipsizeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setEllipsize(null);
TypedArray typedArray = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.CustomEllipsizeTextView,
0, 0
);
try {
postfix = context.getString(
typedArray.getResourceId(R.styleable.CustomEllipsizeTextView_postfix, 0)
);
maxLines = typedArray.getInt(R.styleable.CustomEllipsizeTextView_maxLines, MAX_LINE);
} finally {
typedArray.recycle();
}
}
@Override
public void setText(CharSequence text, BufferType type) {
super.setText(text, type);
originalText = String.valueOf(text);
}
public void setPostfixString(String string) {
postfix = string;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Layout layout = getLayout();
if (layout != null) {
if (layout.getLineCount() > maxLines) {
String ellipsize = ELLIPSIZE_STRING + postfix;
originalText = getText().toString();
if (!TextUtils.isEmpty(originalText) && originalText.length() > 1) {
originalText = originalText.substring(0,
originalText.length() - 1 - ellipsize.length());
setText(originalText + ellipsize);
measure(widthMeasureSpec, heightMeasureSpec);
}
} else {
if (!postfixAdded) {
postfixAdded = true;
setText(originalText + postfix);
}
}
}
}
}
@jdeebee
Copy link

jdeebee commented May 10, 2016

There are 2 issues, at least:

  1. The postfix is always added to the TextView, no matter whether the text is ellipsized or not.
  2. I use this widget in a RecyclerView and on some list item views, the following line causes the IndexOutOfBand exception with the end index being negative (e.g. -4):
originalText = originalText.substring(0,
                            originalText.length() - 1 - ellipsize.length());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment