Last active
September 14, 2017 08:16
-
-
Save PrashamTrivedi/eb56604aba8b5c905b8a45e8a3342d50 to your computer and use it in GitHub Desktop.
Utils for creating spans with minimum texts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.spaniard | |
import android.text.Spannable | |
import android.text.SpannableStringBuilder | |
import android.text.style.CharacterStyle | |
class Spaniard(val originalString: String) { | |
var spannableStringBuilder = SpannableStringBuilder(originalString) | |
inline fun span(crossinline spanFun: Spaniard.() -> Unit): SpannableStringBuilder { | |
spanFun() | |
return spannableStringBuilder | |
} | |
fun addSpan(text: String, span: CharacterStyle, flag: Int= Spannable.SPAN_INCLUSIVE_INCLUSIVE) { | |
val index = originalString.indexOf(text) | |
if (index != -1) { | |
spannableStringBuilder.setSpan(span, index, index+text.length, flag) | |
} | |
} | |
} | |
//Example | |
//Create Spaniard object with whole text and call span | |
val span: SpannableStringBuilder = Spaniard("Whoa, how this works").span { | |
addSpan("Whoa", StyleSpan(Typeface.BOLD), Spannable.SPAN_INCLUSIVE_INCLUSIVE) | |
//Spannable.SPAN_INCLUSIVE_INCLUSIVE is default so you can omit it | |
addSpan("how this",ForegroundColorSpan(ContextCompat.getColor(WhateverContextAvailable, R.color.colorPrimaryDark))) | |
//Or you can pass something else | |
addSpan("works", StrikethroughSpan(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE) | |
//This does nothing as there is no such text above | |
addSpan("Prasham",TextAppearanceSpan(WhateverContextAvailable, R.style.TextAppearance_AppCompat_Body2), | |
Spannable.SPAN_INCLUSIVE_INCLUSIVE) | |
//BTW These flags only matter to EditText and specially while editing the text | |
//In TextView flags are not doing anything. | |
//Read more at | |
//https://stackoverflow.com/questions/9879233/explain-the-meaning-of-span-flags-like-span-exclusive-exclusive | |
} | |
//now on your textview set span and you're ready to go |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use
Step 1: Create Spaniard object and pass full String in constructor
Step 2: call span() method on obect
Step 3: in Span method , call addSpan() methods, pass your desired chunk of full string and Span you want to apply.
Step 4: return value of span method is raw spannable string builder. Which you can use for fun, profit and anything. Like setting a final text.
Thanks