简体   繁体   中英

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>

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.

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);

Set lines tag to your layout android:lines="4"

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:lines="4"                
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

</RelativeLayout>

Write correct "br" html tags

 TextView text =(TextView)findViewById(R.id.text);        
        text .setText(Html.fromHtml("<p align=right> <b> "
                + "<br>" +"Hi!" + "  </br> "
                + "<br> How are you "+" </br>"
                + "<br>I am fine" + " </br> </b> </p>"));

textView.setText(Html.fromHtml(str,Html.FROM_HTML_MODE_COMPACT));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM