Skip to content

Instantly share code, notes, and snippets.

@briangriffey
Created November 13, 2013 22:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briangriffey/7457424 to your computer and use it in GitHub Desktop.
Save briangriffey/7457424 to your computer and use it in GitHub Desktop.
Makes sure text doesn't go beyond the boundaries of its measured height and adjusts itself to the maximum appropriate lines.
package com.vice.viceforandroid.views;
import android.content.Context;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by briangriffey on 11/13/13.
*/
public class CuttingOffTextView extends TextView {
public CuttingOffTextView(Context context) {
super(context);
}
public CuttingOffTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CuttingOffTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
adjustMaxLines();
}
private void adjustMaxLines() {
float size = getTextSize();
TextPaint paint = getPaint();
float textHeight = paint.descent() - paint.ascent();
float measuredHeight = getMeasuredHeight();
if(measuredHeight == 0)
return;
int lines = (int)(measuredHeight/textHeight);
setMaxLines(lines);
setEllipsize(TextUtils.TruncateAt.END);
invalidate();
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
adjustMaxLines();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment