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

时间:2012-09-24 13:45:56

标签: android android-layout textview

我必须分三个部分显示文字,所以我使用了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 个答案:

答案 0 :(得分:15)

您使用<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 :(得分: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);

答案 2 :(得分:1)

将线条标记设置为您的布局   机器人:线=&#34; 4&#34;

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

写出正确的&#34; br&#34; 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>"));

答案 3 :(得分:0)

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

相关问题