Skip to content

Instantly share code, notes, and snippets.

@glureau
Last active June 3, 2019 23:01
Show Gist options
  • Save glureau/39eb458f651a509f7a40af6c2268cb63 to your computer and use it in GitHub Desktop.
Save glureau/39eb458f651a509f7a40af6c2268cb63 to your computer and use it in GitHub Desktop.
private boolean suggestedSizeFitsInSpace(int suggestedSizeInPx, RectF availableSpace) {
CharSequence text = mTextView.getText();
TransformationMethod transformationMethod = mTextView.getTransformationMethod();
if (transformationMethod != null) {
CharSequence transformedText = transformationMethod.getTransformation(text, mTextView);
if (transformedText != null) {
text = transformedText;
}
}
final int maxLines = Build.VERSION.SDK_INT >= 16 ? mTextView.getMaxLines() : -1;
if (mTempTextPaint == null) {
mTempTextPaint = new TextPaint();
} else {
mTempTextPaint.reset();
}
mTempTextPaint.set(mTextView.getPaint());
mTempTextPaint.setTextSize(suggestedSizeInPx);
// Needs reflection call due to being private.
Layout.Alignment alignment = invokeAndReturnWithDefault(
mTextView, "getLayoutAlignment", Layout.Alignment.ALIGN_NORMAL);
final StaticLayout layout = Build.VERSION.SDK_INT >= 23
? createStaticLayoutForMeasuring(
text, alignment, Math.round(availableSpace.right), maxLines)
: createStaticLayoutForMeasuringPre23(
text, alignment, Math.round(availableSpace.right));
// Lines overflow.
if (maxLines != -1 && (layout.getLineCount() > maxLines
|| (layout.getLineEnd(layout.getLineCount() - 1)) != text.length())) {
return false;
}
// Height overflow.
if (layout.getHeight() > availableSpace.bottom) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment