如何将一个视图滑出另一个视图

How to slide a view out of another view

我有一个左上角带有导航菜单的片段。在activity开头,我想逐渐从菜单图标中滑出一个视图(姑且称之为black_view)。

下面是我希望动画与下图一致的粗略分解:

  1. Activity 作为第一张图像开始,black_view 不可见。
  2. black_view从菜单图标后面一点一点慢慢滑出,直到第二张图的点。

>>>


我尝试过的:

我尝试通过使用 TranslateAnimation. However, the whole length of black_view shows up at the start of the animation and this is not what I want. I also saw a couple of sliding animation code snippets like this and this 实现这一点,但它们都遵循 TranlateAnimation 模型(black_view 的整个长度立即显示)。

我怎样才能做到这一点?

PS:如果有任何重要的细节我没有添加,请告诉我。

使用 Transition APISlide 转换可以轻松完成。只需使用 TransitionManager.beginDelayedTransition 方法,然后将黑色视图的可见性从 GONE 更改为 VISIBLE

import androidx.appcompat.app.AppCompatActivity;
import androidx.transition.Slide;
import androidx.transition.Transition;
import androidx.transition.TransitionManager;

public class MainActivity extends AppCompatActivity {

    private ViewGroup parent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        parent = findViewById(R.id.parent);
        parent.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                parent.getViewTreeObserver().removeOnPreDrawListener(this);
                animate();
                return true;
            }
        });
    }

    private void animate() {
        View textView = findViewById(R.id.text);

        Transition transition = new Slide(Gravity.LEFT);
        transition.setDuration(2000);
        transition.setStartDelay(1000);
        TransitionManager.beginDelayedTransition(parent, transition);

        textView.setVisibility(View.VISIBLE);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="Button" />

    <FrameLayout
        android:id="@+id/parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/button">

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#000"
            android:text="hello world"
            android:textColor="#fff"
            android:textSize="22sp"
            android:visibility="gone" />
    </FrameLayout>

</RelativeLayout>

结果:

这里所有 类 来自 androix 包所以代码是向后兼容的。