Skip to content

Instantly share code, notes, and snippets.

@brescia123
Last active May 10, 2023 12:28
Show Gist options
  • Save brescia123/d315af5bd3f4a47c5d548cd9c7de55eb to your computer and use it in GitHub Desktop.
Save brescia123/d315af5bd3f4a47c5d548cd9c7de55eb 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
}
}
@aballano
Copy link

aballano commented Jun 8, 2017

Nice! Some nitpicks:

You could make invisible and gone just call hide to don't repeat so much code.
Having invisible and gone you don't need to expose hide, so you could make it private. Also its javadoc is wrong.
Same for visibleOrHide

@brescia123
Copy link
Author

Thanks for the tips! I updated the gist!

@DmitriyTerekhin
Copy link

Hi, guys! I am pretty new to android. Could you say please how to use it?)

@pablin202
Copy link

Thank you for the gist!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment