Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set text in TextView using Html.fromHtml

I have to show a text in three parts, so i have used Html.fromHtml like this:

txtvw.setText(Html.fromHtml("<p align=right> <b> "
                    + "Hi!" + " </br> <font size=6>"
                    + " How are you "+"</font> </br>"
                    + "I am fine" + "  </b> </p>"));

The HTML is correct but in device it's showing in one line.

my xml declaration of textview is:

   <RelativeLayout
    android:id="@+id/Home"
    android:layout_width="fill_parent"
    android:layout_height="60dp"
    android:background="@drawable/transparentfooter"
    android:layout_above="@+id/bottombar" >


     <TextView 
    android:id="@+id/txt"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:textColor="@android:color/white"/>

    </RelativeLayout>
like image 903
zaiff Avatar asked Sep 24 '12 13:09

zaiff


People also ask

Which method is used to set the text in a TextView?

SetText(String, TextView+BufferType) Sets the text to be displayed using a string resource identifier.

How can I use HTML text in android?

Here is the simple solution to show HTML in TextView in android. Step 1 − Create a new project in Android Studio,go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

What does HTML fromHtml do?

fromHtml. Returns displayable styled text from the provided HTML string. Any <img> tags in the HTML will use the specified ImageGetter to request a representation of the image (use null if you don't want this) and the specified TagHandler to handle unknown tags (specify null if you don't want this).


2 Answers

The way you used the <br> tag is inappropriate. Use the following:

txtvw.setText(Html.fromHtml("<p align=right> <b> "
            + "Hi!" + " <br/> <font size=6>"
            + " How are you "+"</font> <br/>"
            + "I am fine" + "  </b> </p>"));

It should be <br/> and not </br> I have tested this code and it displays the 3 lines as expected.

like image 159
Arun George Avatar answered Oct 16 '22 23:10

Arun George


Html.fromHtml(String source)

now Deprecated from Api-24.

From Api-24 this method changed to

Html.fromHtml(String source,int flags)

So we can use like below from Api 24

txtvw.setText(Html.fromHtml("<p align=right> <b> "
            + "Hi!" + " <br/> <font size=6>"
            + " How are you "+"</font> <br/>"
            + "I am fine" + "  </b> </p>"),Html.FROM_HTML_MODE_LEGACY);
like image 30
Lins Louis Avatar answered Oct 16 '22 22:10

Lins Louis