繁体   English   中英

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

[英]Animate view from top to center of screen

我正在尝试使用翻译动画将图像视图从屏幕顶部移动到屏幕的中心或中间,即当活动开始时,图像视图开始从屏幕顶部移动到屏幕的顶部和底部图像视图空间在屏幕上显示的完全相同,就像我们在相对布局中所做的那样,在布局的 xml 文件中使用标签中心在父级中为真。 通常我们在 facebook 和 whatsapp 应用程序中找到这些动画,它们用于图像翻译或移动图像视图动画。我已经尝试了很多 SO 问题和答案,也谷歌搜索但没有找到合适的解决方案。 到目前为止我所做的如下。请帮助我解决这些问题。谢谢。

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);


            }
        });


    }

假设您有一个位于屏幕左上角的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);
    }
}); 

结果:

在此处输入图片说明

您不会在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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM