Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A custom TextView that can shrink its text size to fit in a single line
/**
* Forked from: http://androidxref.com/4.1.1/xref/frameworks/base/core/java/com/android/internal/widget/DialogTitle.java
* Created by LeoLink on 2014-06-30.
*/
public class SingleLineTextView extends TextView {
public SingleLineTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setSingleLine();
setEllipsize(TextUtils.TruncateAt.END);
}
public SingleLineTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setSingleLine();
setEllipsize(TextUtils.TruncateAt.END);
}
public SingleLineTextView(Context context) {
super(context);
setSingleLine();
setEllipsize(TextUtils.TruncateAt.END);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final Layout layout = getLayout();
if (layout != null) {
final int lineCount = layout.getLineCount();
if (lineCount > 0) {
final int ellipsisCount = layout.getEllipsisCount(lineCount - 1);
if (ellipsisCount > 0) {
final float textSize = getTextSize();
// textSize is already expressed in pixels
setTextSize(TypedValue.COMPLEX_UNIT_PX, (textSize - 1));
// recursion
measure(widthMeasureSpec, heightMeasureSpec);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.