Last active
May 10, 2023 12:28
-
-
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
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
/** 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 | |
} | |
} |
Hi, guys! I am pretty new to android. Could you say please how to use it?)
Thank you for the gist!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the tips! I updated the gist!