从顶部到屏幕中心的动画视图

Animate view from top to center of screen

我正在尝试使用翻译动画将图像视图从屏幕顶部移动到屏幕中央或中间,即当 activity 启动时,图像视图开始从屏幕顶部移动到屏幕中间或中央图像视图的顶部 space 和图像视图的底部 space 在屏幕上显示相等,就像我们在相对布局中所做的那样,在布局的 xml 文件中使用 tag center In Parent true 。一般来说,我们在 facebook 和 whatsapp 应用程序中发现了这些类型的动画,它们用于图像翻译或移动图像视图 animation.i 已经尝试了很多 SO 问答也谷歌搜索但没有找到合适的解决方案。我所做的 following.Please 帮助我解决了这些 issue.thanks.

public class MainActivity extends AppCompatActivity {

    ImageView imageview;


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

        imageview = (ImageView) findViewById(R.id.imagview);

        RelativeLayout root = (RelativeLayout) findViewById(R.id.rel);


        TranslateAnimation anim = new TranslateAnimation(0, 0, 0, 50);
        anim.setInterpolator((new AccelerateDecelerateInterpolator()));
        anim.setAnimationListener(new MyAnimationListener());
        anim.setDuration(500);
        anim.setFillAfter(true);
        imageview.startAnimation(anim);


            }
        });


    }

您没有在 onCreate() 中启动动画,因为用户无法完全看到屏幕。如果您的根视图使用屏幕的整个区域,您也不需要获取根视图。

boolean hasAnimationStarted;

public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus && !hasAnimationStarted) {
        hasAnimationStarted=true;
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        ObjectAnimator translationY = ObjectAnimator.ofFloat(imageview, "y", metrics.heightPixels / 2 - imageview.getHeight() / 2); // metrics.heightPixels or root.getHeight()
        translationY.setDuration(500);
        translationY.start();
    }
}

假设您有一个位于屏幕左上角的 View,我们希望将其动画化到屏幕中央。

布局文件:

<FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/root">

    <View
            android:id="@+id/animated_view"
            android:layout_width="50dp"
            android:background="#6eed57"
            android:layout_height="50dp"/>

</FrameLayout>

onCreate()中:

final View root = findViewById(R.id.root);
final View animatedView = findViewById(R.id.animated_view);

root.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View v) {
        animatedView.animate()
                    .translationX((root.getWidth() - animatedView.getWidth()) / 2)
                    .translationY((root.getHeight() - animatedView.getHeight()) / 2)
                    .setInterpolator(new AccelerateInterpolator())
                    .setDuration(500);
    }
}); 

结果: