下面是一个示例代码,演示了如何使用 Html.fromHtml() 方法设置文本颜色和文本背景色:

TextView textView = findViewById(R.id.textView);

// 设置文本颜色
String textColor = "<font color='#FF0000'>红色文本</font>";
textView.setText(Html.fromHtml(textColor));

// 设置文本背景色
String backgroundColor = "<font style='background-color:#FFFF00'>黄色背景</font>";
textView.setText(Html.fromHtml(backgroundColor));

// 同时设置文本颜色和文本背景色
String textWithColorAndBackground = "<font color='#00FF00' style='background-color:#0000FF'>绿色文本,蓝色背景</font>";
textView.setText(Html.fromHtml(textWithColorAndBackground));

在代码中,首先通过 findViewById() 方法获取到 TextView 的实例。然后,使用 Html.fromHtml() 方法将包含 HTML 标签的文本转换成 Spanned 对象,并通过 setText() 方法设置给 TextView。

在 HTML 标签中,通过 color 属性来设置文本颜色,使用 style='background-color:#RRGGBB' 来设置文本背景色,其中 #RRGGBB 是表示颜色的十六进制值。可以根据需要修改颜色值来实现不同的效果

android textView 通过HtmlfromHtml 设置文本颜色以及文本背景色的示例代码