Skip to content

Instantly share code, notes, and snippets.

@DerTyp7214
Created February 12, 2019 17:44
Show Gist options
  • Save DerTyp7214/819659c2e6b9befbdd49145d9d25c491 to your computer and use it in GitHub Desktop.
Save DerTyp7214/819659c2e6b9befbdd49145d9d25c491 to your computer and use it in GitHub Desktop.
Resize viewgroup height when swiping over it
package com.dertyp7214.experimantaltests
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import /*package*/.dp
import /*package*/.resetHeight
import /*package*/.resizeOnTouch
class Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(/*layout*/)
viewGroup.resizeOnTouch(minHeight = 50.dp(this))
}
override fun onBackPressed() {
viewGroup.resetHeight(50.dp(this))
}
}
import android.content.Context
fun Int.dp(context: Context): Int {
val scale = context.resources.displayMetrics.density
return (this * scale + 0.5f).toInt()
}
import android.transition.ChangeBounds
import android.transition.TransitionManager
import android.view.MotionEvent.ACTION_DOWN
import android.view.MotionEvent.ACTION_MOVE
import android.view.ViewGroup
import android.view.animation.AccelerateDecelerateInterpolator
fun ViewGroup.resizeOnTouch(
remove: Boolean = false,
tolerance: Int = -1,
minHeight: Int = -1,
maxHeight: Int = -1
) {
var allowMove = false
if (remove) setOnTouchListener { _, _ -> true }
else setOnTouchListener { _, event ->
val y = event.y
when (event.action) {
ACTION_DOWN -> {
allowMove = tolerance == -1 || (y >= layoutParams.height - tolerance && y <= layoutParams.height + tolerance)
}
ACTION_MOVE -> {
if (allowMove) {
layoutParams.height = if (minHeight != -1 && y < minHeight) minHeight else {
if (maxHeight != -1 && y > maxHeight) maxHeight else {
val parentHeight = (parent as ViewGroup).height
if (y > parentHeight && parentHeight != -1) parentHeight
else y.toInt()
}
}
requestLayout()
}
}
}
true
}
}
val ViewGroup.isMaxHeight: Boolean
get() = (parent as ViewGroup).height == layoutParams.height
fun ViewGroup.resetHeight(height: Int) {
ChangeBounds().apply {
startDelay = 0
interpolator = AccelerateDecelerateInterpolator()
duration = resources.getInteger(android.R.integer.config_longAnimTime).toLong()
TransitionManager.beginDelayedTransition(this@resetHeight, this)
}
layoutParams.height = height
requestLayout()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment