Unresolved reference: setSpan in Kotlin

Viewed 1494

I want to set symbol * at mandatory field. for that i can use below code line:

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

it is work but i can't set the red color at this symbol *

So i use another example like below :

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)

All code set grate but error come on below line:

str!!.setSpan(ForegroundColorSpan(Color.RED), loc, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)

ERROR

Unresolved reference: setSpan

So How to i resolve this error ??

2 Answers

You need to use SpannableString, something like this:

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

@Alex code work but there is you want to set the position where to show *. So I can use below code. It is show the symbol * at end of the 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);
Related