subrata sharma
subrata sharma

Reputation: 344

change color in substring in kotlin

I want to make "show more" in different colors but, it's not working using spannable in kotlin. please help.

                val mSpannableString = SpannableString("show more")
                val mBlue = ForegroundColorSpan(Color.BLUE)
                mSpannableString.setSpan(mBlue,2,7,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

                holder.MORE.text = "READ MORE"
                if (Expert_answer.length>=300) {

                    holder.description.text = Expert_answer.substring(0,300)+"..."+mSpannableString
                }else{
                    holder.description.text = Expert_answer
                }

Upvotes: 1

Views: 2355

Answers (3)

Dashrath Rathod
Dashrath Rathod

Reputation: 538

You can also create a custom implementation for the span as following.

 val spannable = SpannableStringBuilder(“Text is spantastic!”)
spannable.setSpan(
     ForegroundColorSpan(Color.RED), 
     8, 12, 
     Spannable.SPAN_EXCLUSIVE_INCLUSIVE)

For Your example here

 val showMore = "show more"
        val Expert_answer =
            "sample text  sample text sample text sample text sample text sample text sample text sample text "

        val Expert_answer =Expert_answer.substring(0, 30) + "..." + showmore
        val mSpannableString = SpannableStringBuilder(Expert_answer)

        val mBlue = ForegroundColorSpan(Color.BLUE)
        mSpannableString.setSpan(mBlue, 33, 42, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        abcTitle.text = mSpannableString

enter image description here

Happy Coding!!!

Upvotes: 2

haresh
haresh

Reputation: 1420

I have done this so I may be able to help you here.

   val txtShow ="show"
   val txtMore ="More"
   val spannable = SpannableString(txtShow) // String for which you want to change the color
   spannable.setSpan(ForegroundColorSpan(Color.RED), 0, txtShow.length, 
   Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
   txtMessage.text = TextUtils.concat(txtShow,txtMore)

Let me know if still any help require or stuck.Happy Coding!!!

Upvotes: 7

Dmitrii Leonov
Dmitrii Leonov

Reputation: 1389

Below function will substring input to 300 characters (if it exceeds 300 chars), append "Show more" to the end of it and set value to holder.description.text

private fun setShowMoreIfNeeded(input: String) {
    val maxLenthOfStingShown = 300
    holder.description.text = if (input.length > maxLenthOfStingShown) {
        SpannableStringBuilder()
            .append(input.substring(0, maxLenthOfStingShown))
            .color(Color.BLUE) {append("Show more")}
    } else {
        input
    }
}

Upvotes: 0

Related Questions