在Android中使用Html.fromHtml()突出显示文本颜色?
我正在开发一个应用程序,其中将有一个搜索屏幕用户可以搜索特定关键字,关键字应该是突出显示。 我找到了Html.fromHtml方法。
但我想知道它是否是正确的方法不。
请告诉我你对此的看法。
8个解决方案
179 votes
或者比手动处理Spannable更简单,因为你没有说你想要突出显示背景,只是文字:
String styledText = "This is simple.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);
Christopher Orr answered 2019-05-18T23:48:02Z
34 votes
使用xml资源中的颜色值:
int labelColor = getResources().getColor(R.color.label_color);
String сolorString = String.format("%X", labelColor).substring(2); // !!strip alpha value!!
Html.fromHtml(String.format("text", сolorString), TextView.BufferType.SPANNABLE);
SergeyA answered 2019-05-18T23:48:26Z
12 votes
这可以使用Spannable String来实现。 您需要导入以下内容
import android.text.SpannableString;
import android.text.style.BackgroundColorSpan;
import android.text.style.StyleSpan;
然后,您可以使用以下内容更改文本的背景:
TextView text = (TextView) findViewById(R.id.text_login);
text.setText("");
text.append("Add all your funky text in here");
Spannable sText = (Spannable) text.getText();
sText.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);
这将突出显示位置为1 - 4的红色字符。 希望这可以帮助!
stealthcopter answered 2019-05-18T23:49:02Z
4 votes
替代解决方案:改为使用WebView。 Html很容易使用。
WebView webview = new WebView(this);
String summary = "
Sorry, Madonna gave no results";webview.loadData(summary, "text/html", "utf-8");
Vidar Vestnes answered 2019-05-18T23:49:26Z
2 votes
String name = modelOrderList.get(position).getName(); //get name from List
String text = "" + name + ""; //set Black color of name
/* check API version, according to version call method of Html class */
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
Log.d(TAG, "onBindViewHolder: if");
holder.textViewName.setText(context.getString(R.string._5687982) + " ");
holder.textViewName.append(Html.fromHtml(text));
} else {
Log.d(TAG, "onBindViewHolder: else");
holder.textViewName.setText("123456" + " "); //set text
holder.textViewName.append(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY)); //append text into textView
}
Khyati Fatania answered 2019-05-18T23:49:43Z
0 votes
textview.setText(Html.fromHtml(""+text contain+""));
它将使颜色与html编辑器中的颜色完全一致,只需设置textview并将其与textview值连接即可。 Android不支持span颜色,在编辑器中将其更改为字体颜色,你就可以了。
Naina answered 2019-05-18T23:50:07Z
0 votes
不推荐使用font而不是Html.fromHtml(“”+ content +“”)
mhdtouban answered 2019-05-18T23:50:30Z
0 votes
使您的文字的一部分加下划线和着色
在strings.xml中
put the text here and <u><font color="#your_hexa_color">the underlined colored part here<font><u>
然后在活动中
yourTextView.setText(Html.fromHtml(getString(R.string.text_with_colored_underline)));
和可点击的链接:
text before linktitle of link.
]]>
在你的活动中:
yourTextView.setText(Html.fromHtml(getString(R.string.text_with_link)));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
bsma answered 2019-05-18T23:51:20Z