Skip to content

Instantly share code, notes, and snippets.

@policante
Created August 28, 2020 01:33
Show Gist options
  • Save policante/cc752391120e0eed150f16d8bfe6cc30 to your computer and use it in GitHub Desktop.
Save policante/cc752391120e0eed150f16d8bfe6cc30 to your computer and use it in GitHub Desktop.
Extensão em Kotlin para converter String em SpannableString ou Vice-Versa.
import android.content.Context
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.text.style.TextAppearanceSpan
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
fun String.bold(): SpannableString {
return SpannableString(this).apply {
setSpan(StyleSpan(Typeface.BOLD), 0, [email protected], Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
fun String.color(context: Context, @ColorRes color: Int): SpannableString {
return SpannableString(this).apply {
setSpan(
ForegroundColorSpan(ContextCompat.getColor(context, color)),
0,
[email protected],
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
fun String.color(@ColorInt color: Int): SpannableString {
return SpannableString(this).apply {
setSpan(
ForegroundColorSpan(color),
0,
[email protected],
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
fun String.textAppearance(context: Context, appearance: Int): SpannableString {
return SpannableString(this).apply {
setSpan(
TextAppearanceSpan(context, appearance),
0,
[email protected],
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
//
fun SpannableString.bold(): SpannableString {
return this.apply {
setSpan(StyleSpan(Typeface.BOLD), 0, length, 0)
}
}
fun SpannableString.color(context: Context, @ColorRes color: Int): SpannableString {
return this.apply {
setSpan(ForegroundColorSpan(ContextCompat.getColor(context, color)), 0, length, 0)
}
}
fun SpannableString.color(@ColorInt color: Int): SpannableString {
return this.apply {
setSpan(ForegroundColorSpan(color), 0, length, 0)
}
}
fun SpannableString.textAppearance(context: Context, appearance: Int): SpannableString {
return this.apply {
setSpan(TextAppearanceSpan(context, appearance), 0, length, 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment