Uniform Text Wrapping In Textview
Solution 1:
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
Solution 2:
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
Solution 3:
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.
Solution 4:
The algorithm would be roughly:
- calculate
String
width (withPaint.measureText
or something) - if it is less than container (
TextView
) width, just use it - otherwise divide
String
width by container to know how many"\n"
to enter - with some search algorithm look for a space character the closest to 1/nth of the width (again using
measureText
if the font is not monospace) - substring at that point and repeat point 4 for n-1 (n > 1)
Probably will require some adjustments like using container width by some small percent smaller than real.
Solution 5:
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!
Post a Comment for "Uniform Text Wrapping In Textview"