Extension functions are wonderful! Style the text view the same way again and again? Make it an extension function.
Here is the official Kotlin documentation on extensions: https://kotlinlang.org/docs/extensions.html
And here are my favorite extension functions that I've been using.
fun TextView.setTextOrGone(value: CharSequence?) {
text = value.nullIfBlank.also { visibility = if (it != null) View.VISIBLE else View.GONE }
}
fun TextView.setCompoundDrawableWithTint(
@DrawableRes drawable: Int,
@ColorRes color: Int,
direction: DrawableDirection
) {
TextViewCompat.setCompoundDrawableTintList(
this,
ColorStateList.valueOf(resources.getColor(color))
)
val drawableResource = AppCompatResources.getDrawable(this.context, drawable)
setCompoundDrawablesRelativeWithIntrinsicBounds(
if (direction == DrawableDirection.START) drawableResource else null,
if (direction == DrawableDirection.TOP) drawableResource else null,
if (direction == DrawableDirection.END) drawableResource else null,
if (direction == DrawableDirection.BOTTOM) drawableResource else null
)
}
enum class DrawableDirection {
TOP, BOTTOM, START, END
}
What are your favorite ways to use extensions in Kotlin?