Skip to content

Instantly share code, notes, and snippets.

@qtyq
Created April 24, 2015 00:21
Show Gist options
  • Save qtyq/f092e9269818436b8bf1 to your computer and use it in GitHub Desktop.
Save qtyq/f092e9269818436b8bf1 to your computer and use it in GitHub Desktop.
A method to truncate a string to fit within a TextView in a specific number of lines.
private boolean truncated = false;
private int numLines = 0;
private static final String mEllipsis = "\u2026";
/**
* Truncate a string to fit within a TextView in a certain number of lines.
*/
protected String truncate(String original, TextView tv, int maxLines) {
StringBuffer buffer = new StringBuffer();
numLines = 0;
//calculate the available width of the TextView
int tvWidth = tv.getMeasuredWidth() - tv.getCompoundPaddingLeft() - tv.getCompoundPaddingRight();
//first split the string into multiple lines delimited by \n, then iterate through each line
String[] lines = original.split("\n");
Log.d(TAG, "maxLines=" + maxLines);
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
Log.d(TAG, "current line=" + line);
//measure the total width this line would take up without any wrapping
float lineWidth = tv.getPaint().measureText(line);
//count the number of wrapped lines added by the current line if wrapped within the given width
numLines += Math.ceil(lineWidth / tvWidth);
Log.d(TAG, "numLines=" + numLines);
//this line will not fit in the TextView, need to truncate the line itself
if (numLines > maxLines) {
//calculate the number of lines that are still available in the TextView
int linesLeft = maxLines - (numLines - (int)Math.ceil(lineWidth / tvWidth));
//fit the current line within the remaining number of lines, truncating and adding ellipsis if needed
String truncatedLine = TextUtils.ellipsize(line, tv.getPaint(), (tvWidth - tv.getPaint().measureText(mEllipsis)) * linesLeft, TruncateAt.END).toString();
//if this line was truncated
if (!truncatedLine.equals(line)) {
buffer.append(truncatedLine);
//if this line was able to fit within the remaining number of lines
} else {
buffer.append(line);
}
//the overall string was truncated
truncated = true;
break;
//this line will fit within and fill up all the lines remaining in the TextView
} else if (numLines == maxLines) {
buffer.append(line);
//if there are more lines after this
if (i < lines.length-1) {
truncated = true;
}
break;
//this line will fit within but NOT fill up all the lines remaining (there will be empty lines after after this)
} else { // if (numLines < maxLines)
buffer.append(line);
//if there are more lines and the next line is not just an empty line
if (i < lines.length-2 && !lines[i+1].equals("")) {
buffer.append("\n");
}
continue;
}
}
return buffer.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment