在Android中使用Html.fromHtml()突出显示文本颜色?

我正在开发一个应用程序,其中将有一个search屏幕,用户可以search特定的关键字,该关键字应该突出显示。 我find了Html.fromHtml方法。

但是我想知道它是否正确的做法。

请让我知道你对此的看法。

或者比手动处理Spannable更简单,因为你没有说你想要背景突出显示,只是文本:

 String styledText = "This is <font color='red'>simple</font>."; textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE); 

使用xml资源的颜色值:

 int labelColor = getResources().getColor(R.color.label_color); String сolorString = String.format("%X", labelColor).substring(2); // !!strip alpha value!! Html.fromHtml(String.format("<font color=\"#%s\">text</font>", сolorString), TextView.BufferType.SPANNABLE); 

这可以使用Spannablestring来实现。 您将需要导入以下内容

 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的人物红色。 希望这可以帮助!

替代解决scheme:改为使用WebView。 Html很容易使用。

 WebView webview = new WebView(this); String summary = "<html><body>Sorry, <span style=\"background: red;\">Madonna</span> gave no results</body></html>"; webview.loadData(summary, "text/html", "utf-8"); 
 textview.setText(Html.fromHtml("<font color='rgb'>"+text contain+"</font>")); 

它将给你的颜色正确的HTML编辑器,只需设置textview和连接它的textview值。 Android不支持跨度颜色,在编辑器中将其更改为字体颜色,并且您都将设置为去。

字体被弃用使用span而不是Html.fromHtml(“”+ content +“”)

  String name = modelOrderList.get(position).getName(); //get name from List String text = "<font color='#000000'>" + name + "</font>"; //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 }