sonix
sonix

Reputation: 243

animate hide and show of an android button on scroll events

Whats the best way to animate a button in android based on scroll events?

I have a button which is located in the bottom right corner of the view and I'd like to animate the button to move below the bottom viewport when the user is scrolling down and up, if the user scrolls up.

My Layout:

I used the ObservableScrollView from this example (Synchronise ScrollView scroll positions - android)

<RelativeLayout ...>
    <ObservableScrollView ...> 
        <LinearLayout ...>
            <!-- <Items> -->
        </LinearLayout>
    </ObservableScrollView>
    <Button />
</RelativeLayout>

edit:

attached some scala code

observableScrollView.setScrollViewListener(new ScrollViewListener {
  override def onScrollChanged(scrollView: ObservableScrollView, x: Int, y: Int, oldx: Int, oldy: Int): Unit = {

    val scrollBottom = linearLayout.getHeight - observableScrollView.getHeight - 20

    if (y >= scrollBottom) { // reached bottom
      composeButton.stateChange(STATE_SHOW)
    } else if (y > 0 && oldy > 0 && y > oldy) { // scroll up
      composeButton.stateChange(STATE_HIDE)
    } else if (y > 0 && oldy > 0 && y < oldy) { // scroll down
      composeButton.stateChange(STATE_SHOW)
    }
  }
})

=====

val animationDuration: Int = 1000
lazy val yStartPosition = getY // initialized on first access
var currentState: ComposeButtonState = STATE_SHOW
val animationQueue: AnimatorSet = new AnimatorSet()


def animate(from:Float, to:Float) = {
  val anim = ObjectAnimator.ofFloat(this, "y", from, to)
  anim.setDuration(animationDuration)
  anim.setInterpolator(new OvershootInterpolator())
  animationQueue.play(anim)
  animationQueue.start()
}

def stateChange(state: ComposeButtonState) = {
  if (state != currentState) {
    currentState = state
    state match {
      case STATE_SHOW => animate(yStartPosition + yTranslateInitialValue, yStartPosition)
      case STATE_HIDE => animate(yStartPosition, yStartPosition + yTranslateInitialValue)
    }
  }
}

Upvotes: 0

Views: 3198

Answers (1)

erik
erik

Reputation: 4958

Use an ObjectAnimator with

@Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
       //do something cool
    }

Object Animator example:

ObjectAnimator myAnimation = ObjectAnimator.ofFloat(yourButton, "translationY",
                yourButton.getY(), screenHeight);

Upvotes: 1

Related Questions