I need nice text wrapping in TextView, especially for text in headers.
Text wrapping for TextView might look like this, where the last word is in new line:
You can add a '\n' in your string resouce xml to add a newline so you can managethe wrapping yourself.
Another approach would be to dynamically add the '\n' where you get the string length divided by 2 and search for the next space in either direction and on the first find you just add '\n' there. A hack, but probably work.
Other than that there is not much in Android for Hyphenation or Typography. Propably this post will give you some tips: http://smarter-than-the-average-pierre.blogspot.co.at/2011/10/bad-android-typography-tale-of-text.html
I have modified TextView and created UniformTextView. After investigating of TextView sources I have decided to minimize TextView's width to have preferred lines number.
<pl.dziobas.uniformtextview.UniformTextView
android:text="@string/sample_text"
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:prefLineNumber="2"
style="@style/sample_style" />
It works satisfactorily for me.
Sources are available on github
If you know whats the text in advance (I means if its a hard coded text), you can fix the width of TextView in dp, so that it wraps up properly, or else you may also use android:ems to fix the maximum number of characters in a line. So your TextView can be:
<TextView
android:layout_height="wrap_content"
android:layout_width="100dp"
android:lines="2"/>
OR
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:ems="15"
android:lines="2" />
I hope this helps!
There is an open source project in Github AutoFittextView and in BitBucket AutoScaletextView.
You can change according to your requirement.
I tried the AutoScaleTextview and reached to the below OutPut.
Hope this will help you.
Check out Android's own autoTextSizing for TextView
, added in add API 26 with Support Library that supports from API 14 onwards with app:autoSizeTextType="uniform"
.
Have fun!
https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html
The algorithm would be roughly:
String
width (with Paint.measureText
or something)TextView
) width, just use itString
width by container to know how many "\n"
to entermeasureText
if the font is not monospace)Probably will require some adjustments like using container width by some small percent smaller than real.