Created
November 13, 2013 22:14
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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