【问题标题】:Highlighting Text Color using Html.fromHtml() in Android?在 Android 中使用 Html.fromHtml() 突出显示文本颜色?
【发布时间】:2011-02-13 09:56:48
【问题描述】:

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

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

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

【问题讨论】:

标签: android text highlight textview


【解决方案1】:

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

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

【讨论】:

  • 值得注意的是,Html.fromHtml 比 SpannableString 慢,因为它涉及到解析。但对于简短的文本来说,这并不重要
  • link 似乎有另一种解决方案。请参阅 Legend 的答案。
  • 作为评论,我发现我不需要传递 TextView.BufferType.SPANNABLE 并且它仍然有效。谢谢!
  • 你知道任何 html 编辑器可以为 android 安排长文本。例如,我正在尝试使用此站点 (html.am/html-editors/html-text-editor.cfm),但如果我想查看源代码,它会返回颜色为 &lt;span style="color:#ff0000;"&gt;,这样 android 就不会更改颜色。
  • @mehmet 您大概可以搜索并替换以将 标签更改为具有“颜色”属性的 标签。
【解决方案2】:

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

【讨论】:

  • 做得很好。对于能够使用应用资源中的颜色很有用。
  • 我想强调第二行,你在其中子串颜色十六进制:alpha 值会使颜色设置无效!别忘了!
【解决方案3】:

这可以使用 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 处的字符。希望这会有所帮助!

【讨论】:

    【解决方案4】:
     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
        }
    

    【讨论】:

    • 如何从color.xml中获取字体颜色?
    • int color = getResources().getColor(R.color.any_color_name);
    【解决方案5】:

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

    【讨论】:

    • 由于 fromHTML() 的限制,我正在使用平板电脑应用程序,在 WebView 中显示的每个面板中都有文本。欢迎来到 2020 年代,一切都是网页,包括平板电脑的文本视图!~
    【解决方案6】:

    字体已弃用,使用 span 而不是 Html.fromHtml("&lt;span style=color:red&gt;"+content+"&lt;/span&gt;")

    【讨论】:

      【解决方案7】:

      使部分文本加下划线和着色

      在您的 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>
      

      然后在活动中

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

      【讨论】:

        【解决方案8】:
        textview.setText(Html.fromHtml("<font color='rgb'>"+text contain+"</font>"));
        

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

        【讨论】:

          【解决方案9】:

          首先将您的字符串转换为 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);
                      
          

          【讨论】:

            【解决方案10】:

            同时添加 Kotlin 版本:

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

            演示

            【讨论】:

              猜你喜欢
              • 2010-10-18
              • 2014-12-15
              • 2020-11-06
              • 2016-03-29
              • 1970-01-01
              • 1970-01-01
              • 2014-01-15
              • 2015-07-24
              • 1970-01-01
              相关资源
              最近更新 更多