简体   繁体   English

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

[英]Set text in TextView using Html.fromHtml

I have to show a text in three parts, so i have used Html.fromHtml like this: 我必须分三个部分显示文本,所以我使用了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>"));

The HTML is correct but in device it's showing in one line. HTML是正确的,但在设备中它显示在一行。

my xml declaration of textview is: 我的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>

The way you used the <br> tag is inappropriate. 您使用<br>标签的方式不合适。 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. 它应该是<br/>而不是</br>我已经测试了这个代码并且它按预期显示了3行。

Html.fromHtml(String source)

now Deprecated from Api-24. 现在从Api-24贬值。

From Api-24 this method changed to 从Api-24这个方法改为

Html.fromHtml(String source,int flags)

So we can use like below from Api 24 所以我们可以使用下面的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" 将行标记设置为你的布局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 写出正确的“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>"));

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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