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

sun*_*nil 80 android text highlight textview

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

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

请告诉我你对此的看法.

Chr*_*Orr 192

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

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

  • 值得注意的是,Html.fromHtml比SpannableString慢,因为它涉及解析.但对于简短的文字而言并不重要 (8认同)

Ser*_*eyA 35

使用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); 
Run Code Online (Sandbox Code Playgroud)


ste*_*ter 12

这可以使用Spannable String来实现.您需要导入以下内容

import android.text.SpannableString; 
import android.text.style.BackgroundColorSpan; 
import android.text.style.StyleSpan;
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用以下内容更改文本的背景:

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);
Run Code Online (Sandbox Code Playgroud)

这将突出显示位置1 - 4红色的字符.希望这可以帮助!


mhd*_*ban 6

字体已弃用,请使用 span 代替Html.fromHtml("<span style=color:red>"+content+"</span>")


Vid*_*nes 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");
Run Code Online (Sandbox Code Playgroud)


Khy*_*nia 5

 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
    }
Run Code Online (Sandbox Code Playgroud)

  • 如何从 color.xml 获取字体颜色? (2认同)