使用Html.fromHtml在TextView中设置文本

15

我需要将一个文本拆分成三部分展示,因此我使用了Html.fromHtml,代码如下:

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

HTML代码正确,但在设备上显示为单行。

我的textview的XML声明是:

   <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>
4个回答

17

您使用<br>标签的方式是不恰当的。请使用以下内容:

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

应该使用 <br/> 而不是 </br>。我已经测试了这段代码,它按预期显示了3行。


1
是的,它可以工作,但右对齐没有生效,你能告诉我出了什么问题吗? - zaiff
2
似乎在TextView中不支持HTML文本的对齐方式。您可以尝试以下链接中的一些技巧来获得对齐方式。我建议最好的方法是使用“Gravity”。尝试使用'txtvw.setGravity(Gravity.RIGHT)'. 请查看以下链接:https://dev59.com/Pm865IYBdhLWcg3wUs7z 和https://dev59.com/g3A75IYBdhLWcg3wi5sr - Arun George

2
Html.fromHtml(String source)

现在从Api-24开始已经被弃用。

从Api-24开始,这个方法已经改变为

Html.fromHtml(String source,int flags)

所以从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);

1

在您的布局中设置行标签 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>

编写正确的“br”HTML标签。

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

0

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接