Kotlin中的未解决引用:setSpan

3
我想在必填字段中设置符号*。为此,我可以使用以下代码行:

我要在必填字段中设置*号。为此,我可以使用以下代码行:

hint_mobile!!.setText(Html.fromHtml(resources.getString(R.string.mobile_number) + "<sup> * </sup>"));

这段代码是有效的,但我无法将星号*设置为红色。

所以我使用了另一个示例,如下:

hint_mobile!!.setText(resources.getString(R.string.mobile_number))
        val str = hint_mobile!!.text.toString()
        val loc = hint_mobile!!.text.toString().indexOf("*")
        str!!.setSpan(ForegroundColorSpan(Color.RED), loc, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)

所有的代码都很好,但是在下面这行出现了错误:
str!!.setSpan(ForegroundColorSpan(Color.RED), loc, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)

错误

Unresolved reference: setSpan

那么我该如何解决这个错误呢?

1
str 是一个字符串。String 类没有 setSpan 方法。您可以通过在正确的对象上调用 setSpan 来解决此错误。 - yole
2个回答

2
你需要使用SpannableString,类似如下方式:
val spannableString = SpannableString("${resources.getString(R.string.mobile_number)} *")
val loc = spannableString.toString().indexOf("*")
spannableString.setSpan(ForegroundColorSpan(Color.RED), loc, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
hint_mobile!!.setText(spannableString.toString())

如果我使用你的代码,那么会出现以下错误:**无法启动活动 ComponentInfo{com.addcontectdetail/com.addcontectdetail.MainActivity}:java.lang.IndexOutOfBoundsException: setSpan (-1 ... 1) 在 0 之前开始**。 - Joker
因为'loc'的值为-1,这意味着在您的hint_mobile textview中没有找到'*'。 - Alex
好的,我明白了。谢谢 :) - Joker

0

@Alex的代码可以工作,但是你可能想要设置显示*的位置。因此,我可以使用下面的代码。它会在String的末尾显示符号*

        var simple : String? = resources.getString(R.string.mobile_number)

        var colored : String?  = " *"

        var builder = SpannableStringBuilder()

        builder.append(simple)
        var start = builder.length
        builder.append(colored)
        var end = builder.length

        builder.setSpan(ForegroundColorSpan(Color.RED), start, end,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

        hint_mobile!!.setText(builder);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接