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

发布于 2024-08-30 14:18:37 字数 131 浏览 4 评论 0原文

我正在开发一个应用程序,其中会有一个搜索屏幕 用户可以在其中搜索特定关键字,并且该关键字应该是 突出显示。我找到了 Html.fromHtml 方法。

但我想知道这是否是正确的做法或 不是。

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

I am developing an application in which there will be a search screen
where user can search for specific keywords and that keyword should be
highlighted. I have found Html.fromHtml method.

But I will like to know whether its the proper way of doing it or
not.

Please let me know your views on this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

余厌 2024-09-06 14:18:37

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

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

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);
命比纸薄 2024-09-06 14:18:37

使用 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); 

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); 
梦里°也失望 2024-09-06 14:18:37

这可以使用 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("Your text here");
Spannable sText = (Spannable) text.getText();
sText.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);

这将以红色突出显示 pos 1 - 4 处的字符。希望这有帮助!

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!

踏月而来 2024-09-06 14:18:37

字体已弃用,请使用 span 代替 Html.fromHtml(""+content+"")

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

草莓味的萝莉 2024-09-06 14:18:37

替代解决方案:使用 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");

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");
萌︼了一个春 2024-09-06 14:18:37
 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
    }
 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
    }
烂人 2024-09-06 14:18:37

部分文本加下划线并着色,

要在 strings.xml 中使

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

然后在活动中

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

和可点击链接中:

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

以及在您的活动中:

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

To make part of your text underlined and colored

in your strings.xml

<string name="text_with_colored_underline">put the text here and <u><font color="#your_hexa_color">the underlined colored part here<font><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());
心房敞 2024-09-06 14:18:37

首先将字符串转换为 HTML,然后将其转换为 spannable。按照以下代码的建议进行操作。

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

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);
            
夜访吸血鬼 2024-09-06 14:18:37
textview.setText(Html.fromHtml("<font color='rgb'>"+text contain+"</font>"));

它将给出与您在 html 编辑器中所做的颜色完全相同的颜色,只需设置 textview 并将其与 textview 值连接即可。 Android 不支持跨度颜色,在编辑器中将其更改为字体颜色即可。

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.

最舍不得你 2024-09-06 14:18:37

还添加 Kotlin 版本:

  • 从资源获取文本 (strings.xml)
  • 从资源获取颜色 (colors.xml)
  • “获取十六进制”作为扩展移动
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)
    }
}

和 Kotlin 扩展(使用删除 alpha):

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

演示

演示

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

生生不灭 2024-09-06 14:18:37

我发现直接使用十六进制颜色对应的负整数十进制也可以渲染不透明:

val str=String.format("<font color=\"%s\">Highlighting</font>",
        //convert to the negative integer decimal
        context.getColor(R.color.highlight).toString())
textView.text = Html.fromHtml(str,Html.FROM_HTML_MODE_COMPACT)

I found that using the negative integer decimal corresponding to the hexadecimal color directly can also render without transparency:

val str=String.format("<font color=\"%s\">Highlighting</font>",
        //convert to the negative integer decimal
        context.getColor(R.color.highlight).toString())
textView.text = Html.fromHtml(str,Html.FROM_HTML_MODE_COMPACT)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文