Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slide a view in and out in android

I'm trying to make a view (Linear view with some buttons in - R.id.playerControl) slide in and out based on the context of other events in the activity.

For this purpose I've got a selectMediaItem method which should show or hide the view when the user selects or deselects an item respectively.

I'm new with animation in android and I'm having trouble getting this to work for two reasons:

  1. The view remains on screen outside the animation time, so when it has finished sliding out it jumps back in - then when requested to slide in it jumps out to slide back in.

  2. There is a permanent black space on the screen as the view disappears. I'd like the view to fill space when when visible and be GONE when not. To this end I'd like the layout to change with the animation as well so that it appears to push other things out of the way.

My Code:

protected void selectMediaItem( ItemHandle item ) {

    if (item != null) {
        if (toPlay == null) {
            View playerControl = findViewById(R.id.playerControl);
            Animation slideInAdmination = AnimationUtils.loadAnimation(this, R.anim.slide_in);
            playerControl.startAnimation(slideInAdmination);
        }
    }
    else {
        if (toPlay != null) {
            View playerControl = findViewById(R.id.playerControl);
            Animation slideInAdmination = AnimationUtils.loadAnimation(this, R.anim.slide_out);
            playerControl.startAnimation(slideInAdmination);
        }
    }
    toPlay = item;
}

slide_in.xml

    <translate
        android:duration="1000"
        android:fromYDelta="100%p"
        android:toYDelta="0" />


</set>

Is there a simple way to slide a view into place and slide it out again?

like image 718
Philip Couling Avatar asked May 27 '13 17:05

Philip Couling


1 Answers

I would highly suggest you to use Property Animations. Your sample code would be like.

mSlidInAnimator = ObjectAnimator.ofFloat(mSlidingView, "translationY", 0);
mSlidInAnimator.setDuration(200);
mSlidInAnimator.start();

mSlidOutAnimator = ObjectAnimator.ofFloat(mSlidingView, "translationY", newPosOfView);
mSlidOutAnimator.setDuration(200);
mSlidOutAnimator.start();

"translationY" means up/down animation. Use "translationX" for right left animation.

Here newPosOfView would be a position relative to your default position of view. For example if you want to move your view 50dp down, it would be 50dp in pixels. In slideInAnimator, pos is 0 because you want to move to orignal position of view.

Read the documentation carefully, its very helpful.

like image 155
Shashank Tomar Avatar answered Sep 18 '22 22:09

Shashank Tomar