Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sizing an Android multi-line TextView

I have an Activity where I want to display a heading that takes up the top quarter of the app and displays a dynamic set of text. In some cases it'll all fit on one line and I'd like the font size to get sized up so it's large and easy to read. In some cases it'll be on multiple lines (usually less than 4) and need to be smaller.

The complication is that if I explicitly set the newlines in setText sometimes it will insert a newline where I didn't expect one, i.e.:

"My first line of text\nMy Second line of text"
Might get turned into (it's right adjusted in this version):
"My first line of
             text
   My second line
          of text"

I'm not sure how to go about either keeping the TextView from trying to insert newlines or letting it just take care of formatting the whole thing. If I set some text to be one really long single word it'll insert a newline in the middle at some chosen point. And other times I just sort of randomly get the last few lines of text.

Should I just explicitly set the font size to be really small to get it laid out correctly and then manually adjust the size? Is there a 'best practice' that I should use for this? If I set the font size to be a reasonably large font it kind of works but it would be nice to figure out what the 'right' way to do this would be. And I'd rather not have to manually add in 4 single line TextViews and format them myself.

The layout xml I'm using is:

<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_marginTop="10dip"
        android:layout_marginRight="8dip"
        android:singleLine="false"
        android:ellipsize="marque"
        android:gravity="right|bottom"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textSize="30sp"
/>
like image 756
William Avatar asked Oct 22 '10 21:10

William


1 Answers

You could count the String lenght and set the text size to fit the best size for each lenght

something in this form

if(myString.length()==40){
    myTextview.setTextSize(11);
else if(myString.length()==25){
    myTextview.setTextSize(16);
...

I hope this helps.

like image 162
Silverstorm Avatar answered Sep 19 '22 18:09

Silverstorm