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:

  • 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.

  • 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?


    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.


    You need to add:

    slideInAdmination.setFillerAfter(true)
    

    before you call startAnimation() . This Causes the view to remain in its new position after the animation.

    链接地址: http://www.djcxy.com/p/71730.html

    上一篇: 卷页从左到右的android

    下一篇: 如何在android中滑入和滑出视图