我有简单的HTML:

<h2>Title</h2><br>
<p>description here</p>

我想在TextView中显示HTML样式的文本。如何做到这一点?


当前回答

每当您编写自定义文本视图时,基本的HTML设置文本功能将从某些设备上消失。

因此,我们需要执行以下附加步骤,使其有效

public class CustomTextView extends TextView {

    public CustomTextView(..) {
        // other instructions
        setText(Html.fromHtml(getText().toString()));
    }
}

其他回答

为strings.xml文件中的字符串使用CData部分以在TextView中实际显示html内容的最佳方法。下面的代码片段将为您提供大致思路。

//in string.xml file
<string name="welcome_text"><![CDATA[<b>Welcome,</b> to the forthetyroprogrammers blog Logged in as:]]> %1$s.</string>

//and in Java code
String welcomStr=String.format(getString(R.string.welcome_text),username);
tvWelcomeUser.setText(Html.fromHtml(welcomStr));

即使在使用string.format方法格式化文本之后,字符串文本中的CData部分也会保持html标记数据的完整性。因此,Html.fromHtml(str)工作正常,您将在欢迎消息中看到粗体文本。

输出:

欢迎来到您最喜爱的音乐应用商店。登录身份:username

我知道这个问题很老了。这里的其他答案建议使用Html.fromHtml()方法。我建议您使用androidx.core.text.HtmlCompat包中的HtmlCompat.fromHtml()。因为这是Html类的向后兼容版本。

示例代码:

import androidx.core.text.HtmlCompat;
import android.text.Spanned;
import android.widget.TextView;

String htmlString = "<h1>Hello World!</h1>";

Spanned spanned = HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_COMPACT);

TextView tvOutput = (TextView) findViewById(R.id.text_view_id);

tvOutput.setText(spanned);

通过这种方式,您可以避免Android API版本检查,并且它很容易使用(单行解决方案)。

如果您希望能够通过xml配置它,而不需要对java代码进行任何修改,您可能会发现这个想法很有用。只需从构造函数调用init并将文本设置为html

public class HTMLTextView extends TextView {
    ... constructors calling init...
    private void init(){
       setText(Html.fromHtml(getText().toString()));
    }    
}

xml格式:

<com.package.HTMLTextView
android:text="@string/about_item_1"/>
public class HtmlTextView extends AppCompatTextView {

public HtmlTextView(Context context) {
    super(context);
    init();
}

private void init(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        setText(Html.fromHtml(getText().toString(), Html.FROM_HTML_MODE_COMPACT));
    } else {
        setText(Html.fromHtml(getText().toString()));
    }
 }
}

更新以上答案

如果在项目中使用androidx.*类,则应使用HtmlCompat.fromHtml(文本,标志)。

方法来源:

@NonNull
    public static Spanned fromHtml(@NonNull String source, @FromHtmlFlags int flags) {
        if (Build.VERSION.SDK_INT >= 24) {
            return Html.fromHtml(source, flags);
        }
        //noinspection deprecation
        return Html.fromHtml(source);
    }

使用HtmlCompat.fromHtml比使用Html.fromHtml更好,因为代码更少-只有一行代码,建议使用它。