如何在android中滑入和滑出视图

Phi*_*ing 7 java android android-animation

我正在尝试根据活动中其他事件的上下文进行视图(带有一些按钮的线性视图 - R.id.playerControl)滑入和滑出.

为此,我有一个selectMediaItem方法,当用户分别选择或取消选择一个项目时,该方法应显示或隐藏视图.

我是android中的动画新手,我因为两个原因而无法使用它:

  1. 视图在动画时间之外保留在屏幕上,因此当它完成滑出后会跳回 - 然后当请求滑入时它跳出来滑回.

  2. 当视图消失时,屏幕上会有一个永久的黑色空间.我希望视图在可见时填充空间,GONE何时不可用.为此,我希望布局能够随动画一起改变,以便它可以将其他东西推开.

我的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

slide_in.xml

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


</set>
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法将视图滑动到位并再次滑出?

Sha*_*mar 5

我强烈建议您使用Property Animations。您的示例代码将是这样的。

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

mSlidOutAnimator = ObjectAnimator.ofFloat(mSlidingView, "translationY", newPosOfView);
mSlidOutAnimator.setDuration(200);
mSlidOutAnimator.start();
Run Code Online (Sandbox Code Playgroud)

“translationY”表示向上/向下动画。对左右动画使用“translationX”。

这里 newPosOfView 将是相对于您的默认视图位置的位置。例如,如果您想将视图向下移动 50dp,则它的像素为 50dp。在 slideInAnimator 中,pos 为 0,因为您想移动到视图的原始位置。

仔细阅读文档,很有帮助。