Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muhammad-farhan-bakht/5d4f4366190ae0d0b21f2f15464e8209 to your computer and use it in GitHub Desktop.
Save muhammad-farhan-bakht/5d4f4366190ae0d0b21f2f15464e8209 to your computer and use it in GitHub Desktop.
Useful Android Kotlin Extension functions to easily change the visibility of a View
/** Set the View visibility to VISIBLE and eventually animate the View alpha till 100% */
fun View.visible(animate: Boolean = true) {
if (animate) {
animate().alpha(1f).setDuration(300).setListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator) {
super.onAnimationStart(animation)
visibility = View.VISIBLE
}
})
} else {
visibility = View.VISIBLE
}
}
/** Set the View visibility to INVISIBLE and eventually animate view alpha till 0% */
fun View.invisible(animate: Boolean = true) {
hide(View.INVISIBLE, animate)
}
/** Set the View visibility to GONE and eventually animate view alpha till 0% */
fun View.gone(animate: Boolean = true) {
hide(View.GONE, animate)
}
/** Convenient method that chooses between View.visible() or View.invisible() methods */
fun View.visibleOrInvisible(show: Boolean, animate: Boolean = true) {
if (show) visible(animate) else invisible(animate)
}
/** Convenient method that chooses between View.visible() or View.gone() methods */
fun View.visibleOrGone(show: Boolean, animate: Boolean = true) {
if (show) visible(animate) else gone(animate)
}
private fun View.hide(hidingStrategy: Int, animate: Boolean = true) {
if (animate) {
animate().alpha(0f).setDuration(300).setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
super.onAnimationEnd(animation)
visibility = hidingStrategy
}
})
} else {
visibility = hidingStrategy
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment