Created
April 13, 2018 18:03
-
-
Save fabio-filho/348742d035273557145f5860d4af867b to your computer and use it in GitHub Desktop.
Card View Easy Collapsible - With Kotlin =D
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
// Usage - MainActivity | |
val collapsible = myCardView.buildCollapsible() | |
myButton.onClick { | |
collapsible.toggle() | |
} | |
// ============================================================================================================================ | |
package your_package | |
import android.animation.ValueAnimator | |
import android.support.v7.widget.CardView | |
import android.view.ViewTreeObserver | |
class CardViewCollapsible(val cardView: CardView) { | |
private var compactHeight = 0 | |
internal var expandedHeight = 0 | |
init { | |
cardView.viewTreeObserver.addOnPreDrawListener( | |
object : ViewTreeObserver.OnPreDrawListener { | |
override fun onPreDraw(): Boolean { | |
cardView.viewTreeObserver.removeOnPreDrawListener(this) | |
compactHeight = cardView.height | |
if(expandedHeight == 0) expandedHeight = compactHeight * 2 | |
return true | |
} | |
}) | |
} | |
private fun collapseView() { | |
val anim = ValueAnimator.ofInt( | |
cardView.measuredHeightAndState, compactHeight) | |
anim.addUpdateListener { valueAnimator -> | |
val animatedValue = valueAnimator.animatedValue as Int | |
val layoutParams = cardView.layoutParams | |
layoutParams.height = animatedValue | |
cardView.layoutParams = layoutParams | |
} | |
anim.start() | |
} | |
private fun expandView(height: Int) { | |
val anim = ValueAnimator.ofInt( | |
cardView.measuredHeightAndState, height) | |
anim.addUpdateListener { valueAnimator -> | |
val animatedValue = valueAnimator.animatedValue as Int | |
val layoutParams = cardView.layoutParams | |
layoutParams.height = animatedValue | |
cardView.layoutParams = layoutParams | |
} | |
anim.start() | |
} | |
fun toggle() { | |
if (cardView.height == compactHeight) | |
expandView(expandedHeight) | |
else | |
collapseView() | |
} | |
} | |
fun CardView.buildCollapsible(): CardViewCollapsible { | |
return CardViewCollapsible(this) | |
} | |
fun CardView.buildCollapsible(height: Int): CardViewCollapsible { | |
val collapsible = CardViewCollapsible(this) | |
collapsible.expandedHeight = height | |
return collapsible | |
} | |
// adapted from: https://medium.com/@akshay.shinde/cardview-expand-collapse-cd10916bb77c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment