我不知道如何使TextView上的特定文本变成粗体。

是这样的

txtResult.setText(id+" "+name);

我希望输出是这样的:

1111年尼尔

id和名称是我从数据库中检索值的变量,我想将id改为粗体,但只有id,所以名称不会受到影响,我不知道如何做到这一点。


当前回答

val phone = "+45xxxxxx"

val phoneText = "<font color=#757B7F><b>${phone}</b></font>"

val wholeString = requireActivity().resources.getString(R.string.loginwith)+" "+phoneText

其他回答

当在list/recycler中搜索char时,使字符串的第一个char可扩展

拉维和阿杰

以前突出显示像这样,但我想像下面

ravi和ajay OR ravi和ajay

为此,我搜索单词长度,如果它等于1,我将主字符串分离成单词并计算单词开始位置,然后我搜索单词以char开头。

 public static SpannableString colorString(int color, String text, String... wordsToColor) {
    SpannableString coloredString = new SpannableString(text);

    for (String word : wordsToColor) {

        Log.e("tokentoken", "-wrd len-" + word.length());
        if (word.length() !=1) {
            int startColorIndex = text.toLowerCase().indexOf(word.toLowerCase());
            int endColorIndex = startColorIndex + word.length();
            try {
                coloredString.setSpan(new ForegroundColorSpan(color), startColorIndex, endColorIndex,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            } catch (Exception e) {
                e.getMessage();
            }
        } else {
            int start = 0;

            for (String token : text.split("[\u00A0 \n]")) {
                if (token.length() > 0) {
                    start = text.indexOf(token, start);
                   // Log.e("tokentoken", "-token-" + token + "   --start--" + start);
                    char x = token.toLowerCase().charAt(0);
                    char w = word.toLowerCase().charAt(0);
                   // Log.e("tokentoken", "-w-" + w + "   --x--" + x);

                    if (x == w) {
                        // int startColorIndex = text.toLowerCase().indexOf(word.toLowerCase());
                        int endColorIndex = start + word.length();
                        try {
                            coloredString.setSpan(new ForegroundColorSpan(color), start, endColorIndex,
                                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                        } catch (Exception e) {
                            e.getMessage();
                        }
                    }
                }
            }

        }

    }

    return coloredString;
}

根据@mladj0ni的回答,我得到了下面的代码。问题是如果你使用String。格式,它剥离了HTML标记,所以你必须转义strings.xml中的括号符号:

strings.xml:

<string name="welcome_messages">Hello, %1$s!你有&lt;b>%2$d新消息&lt;/b>.</string> .</string> .

code.java:

String unspanned = String.format(Locale.US, "%s%s", getResources().getString(R.string. welcome_messages), 99);

Spanned spanned;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
    spanned = Html.fromHtml(unspanned, Html.FROM_HTML_MODE_LEGACY);
} else {
    spanned = Html.fromHtml(unspanned);
}

textView.setText(spanned);

它比SpannableStringBuilder简单。至于性能,如果只显示一个字符串,那么用户不会注意到解析它所花费的额外毫秒。

请在这里查看文档。

这是我的完整的解决方案,动态字符串值与大小写检查。

/**
 * Makes a portion of String formatted in BOLD.
 *
 * @param completeString       String from which a portion needs to be extracted and formatted.<br> eg. I am BOLD.
 * @param targetStringToFormat Target String value to format. <br>eg. BOLD
 * @param matchCase Match by target character case or not. If true, BOLD != bold
 * @return A string with a portion formatted in BOLD. <br> I am <b>BOLD</b>.
 */
public static SpannableStringBuilder formatAStringPortionInBold(String completeString, String targetStringToFormat, boolean matchCase) {
    //Null complete string return empty
    if (TextUtils.isEmpty(completeString)) {
        return new SpannableStringBuilder("");
    }

    SpannableStringBuilder str = new SpannableStringBuilder(completeString);
    int start_index = 0;

    //if matchCase is true, match exact string
    if (matchCase) {
        if (TextUtils.isEmpty(targetStringToFormat) || !completeString.contains(targetStringToFormat)) {
            return str;
        }

        start_index = str.toString().indexOf(targetStringToFormat);
    } else {
        //else find in lower cases
        if (TextUtils.isEmpty(targetStringToFormat) || !completeString.toLowerCase().contains(targetStringToFormat.toLowerCase())) {
            return str;
        }

        start_index = str.toString().toLowerCase().indexOf(targetStringToFormat.toLowerCase());
    }

    int end_index = start_index + targetStringToFormat.length();
    str.setSpan(new StyleSpan(BOLD), start_index, end_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return str;
}

如。completeString = "I am BOLD"

情况下,我 if *targetStringToFormat* = "bold" and *matchCase* = true

返回“I am BOLD”(因为BOLD != BOLD)

案例二世 if *targetStringToFormat* = "bold" and *matchCase* = false

返回“I am BOLD”

应用:

myTextView.setText(formatAStringPortionInBold("I am BOLD", "bold", false))

希望有帮助!

我来这里是为了提供一个最新的解决方案,因为我对现有的答案不满意。 我需要一些可以用于翻译文本的东西,并且没有使用Html.fromHtml()的性能影响。 如果您正在使用Kotlin,这里有一个扩展函数,可以轻松地将文本的多个部分设置为粗体。这就像Markdown一样工作,如果需要,可以扩展到支持其他Markdown标签。

val yourString = "**This** is your **string**.".makePartialTextsBold()
val anotherString = getString(R.string.something).makePartialTextsBold()

/**
 * This function requires that the parts of the string that need
 * to be bolded are wrapped in ** and ** tags
 */
fun String.makePartialTextsBold(): SpannableStringBuilder {
    var copy = this
    return SpannableStringBuilder().apply {
        var setSpan = true
        var next: String
        do {
            setSpan = !setSpan
            next = if (length == 0) copy.substringBefore("**", "") else copy.substringBefore("**")
            val start = length
            append(next)
            if (setSpan) {
                setSpan(StyleSpan(Typeface.BOLD), start, length,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }
            copy = copy.removePrefix(next).removePrefix("**")
        } while (copy.isNotEmpty())
    }
}

这不是最简单的解决方案吗?

<string name="string">Please provide your <b>Name</b> properly</string>

只要使用你想要的字符串:)

结果如下所示:

请填写您的姓名