I'm looking for an optimal way to resize wrapping text in a TextView
so that it will fit within its getHeight and getWidth bounds. I'm not simply looking for a way to wrap the text- I want to make sure it both wraps and is small enough to fit entirely on the screen.
I've seen a few cases on StackOverflow where auto resizing was needed, but they are either very special cases with hack solutions, have no solution, or involve re-drawing the TextView
recursively until it is small enough (which is memory intense and forces the user to watch the text shrink step-by-step with every recursion).
But I'm sure somebody out there has found a good solution that doesn't involve what I'm doing: writing several heavy routines that parse and measure the text, resize the text, and repeat until a suitably small size has been found.
What routines does TextView
use to wrap the text? Couldn't those be somehow used to predict whether text will be small enough?
tl;dr: is there a best-practice way to auto-resize a TextView
to fit, wrapped, in its getHeight and getWidth bounds?
I just created the following method (based on the ideas of Chase) which might help you if you want to draw text to any canvas:
This could be used e.g. in any onDraw() method of any custom view.
From June 2018 Android officially started supporting this feature for Android 4.0 (API level 14) and higher.
Check it out at: Autosizing TextViews
With Android 8.0 (API level 26) and higher:
Programmatically:
Android versions prior to Android 8.0 (API level 26):
Programmatically:
Attention: TextView must have layout_width="match_parent" or absolute size!
I wrote a blog post about this.
I created a component called
ResizableButton
based on Kirill Grouchnikov's blog post about custom components used in the new android market app. I placed the src code here.On the other hand, mosabua read my post and told me he was going to open source his implementation which was faster than mine. I hope he release it soon enough :)
Here's a simple solution that uses TextView itself with a TextChangedListened added to it:
This approach will increase or decrease the font size as needed to fit the text, respecting the MIN_SP and MAX_SP bounds received as parameters.
My method is:
For example:
Thanks to Chase and onoelle, for the lazy programmers, let me post here a working version of their fantastic merged code, adapted on a Button, instead of a TextView.
Substitute all your Buttons (not ImageButtons) with AutoResizeTextButtons and the same boring problem is fixed for them too.
Here is the code. I just removed the imports.
Usage:
put a AutoResizeTextButton inside your xml in replace of a normal Button, without changing anything else. Inside the onCreate() put (for example):