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

我正在开发一个应用程序,其中将有一个搜索屏幕 在哪里用户可以搜索特定的关键字和关键字应该是 我已经找到了 Html.from Html 方法。

但我想知道这样做是否正确 没有。

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

122507 次浏览

This can be achieved using a Spannable String. You will need to import the following

import android.text.SpannableString;
import android.text.style.BackgroundColorSpan;
import android.text.style.StyleSpan;

And then you can change the background of the text using something like the following:

TextView text = (TextView) findViewById(R.id.text_login);
text.setText("");
text.append("Your text here");
Spannable sText = (Spannable) text.getText();
sText.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);

Where this will highlight the charecters at pos 1 - 4 with a red color. Hope this helps!

Alternative solution: Using a WebView instead. Html is easy to work with.

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");

Or far simpler than dealing with Spannables manually, since you didn't say that you want the background highlighted, just the text:

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

Using color value from xml resource:

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);
textview.setText(Html.fromHtml("<font color='rgb'>"+text contain+"</font>"));

It will give the color exactly what you have made in html editor , just set the textview and concat it with the textview value. Android does not support span color, change it to font color in editor and you are all set to go.

font is deprecated use span instead Html.fromHtml("<span style=color:red>"+content+"</span>")

 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
}

To make part of your text underlined and colored

in your strings.xml

<string name="text_with_colored_underline">put the text here and &lt;u>&lt;font color="#your_hexa_color">the underlined colored part here&lt;font>&lt;u></string>

then in the activity

yourTextView.setText(Html.fromHtml(getString(R.string.text_with_colored_underline)));

and for clickable links:

<string name="text_with_link"><![CDATA[<p>text before link<a href=\"http://www.google.com\">title of link</a>.<p>]]></string>

and in your activity:

yourTextView.setText(Html.fromHtml(getString(R.string.text_with_link)));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance());

First Convert your string into HTML then convert it into spannable. do as suggest the following codes.

 Spannable spannable = new SpannableString(Html.fromHtml(labelText));
                    

spannable.setSpan(new ForegroundColorSpan(Color.parseColor(color)), spannable.toString().indexOf("•"), spannable.toString().lastIndexOf("•") + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            

Adding also Kotlin version with:

  • getting text from resources (strings.xml)
  • getting color from resources (colors.xml)
  • "fetching HEX" moved as extension
fun getMulticolorSpanned(): Spanned {
// Get text from resources
val text: String = getString(R.string.your_text_from_resources)


// Get color from resources and parse it to HEX (RGB) value
val warningHexColor = getHexFromColors(R.color.your_error_color)


// Use above string & color in HTML
val html = "<string>$text<span style=\"color:#$warningHexColor;\">*</span></string>"


// Parse HTML (base on API version)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(html)
}
}

And Kotlin extension (with removing alpha):

fun Context.getHexFromColors(
colorRes: Int
): String {
val labelColor: Int = ContextCompat.getColor(this, colorRes)
return String.format("%X", labelColor).substring(2)
}

Demo

demo