Android - 在不设置imageView的情况下为图像设置动画

时间:2018-05-21 09:52:06

标签: android animation

在我的应用程序中,我想要为从一侧流入并在另一侧流出的图像设置动画。我用来为下面的代码中的背景设置动画,但是在那个方法中我在我的activity_main中设置了一个imageView,当动画图像被设置在屏幕上时,我不知道在哪里放置一个imageView:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        final ImageView backgroundOne = (ImageView) findViewById(R.id.background_one);
        final ImageView backgroundTwo = (ImageView) findViewById(R.id.background_two);

        final ValueAnimator animator = ValueAnimator.ofFloat(1.0f, 0.0f);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setInterpolator(new LinearInterpolator());
        animator.setDuration(10000L);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                final float progress = (float) animation.getAnimatedValue();
                final float width = backgroundOne.getWidth();
                final float translationX = width * progress;
                backgroundOne.setTranslationX(translationX);
                backgroundTwo.setTranslationX(translationX - width);
            }
        });
        animator.start();

    }

}

1 个答案:

答案 0 :(得分:0)

使用动态插入的图像(image_layout.xml)创建单独的布局:

<ImageView
    android:id="@+id/anim_image"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:src="..."/>

接下来,使用“inflater”:

ViewGroup mainLayout = (ViewGroup) findViewById(R.id.main);
    v = (ViewGroup) getLayoutInflater().inflate(R.layout.image_layout, mainLayout, false);
    mainLayout.addView(v);

    final ImageView backgroundOne = (ImageView) v.findViewById(R.id.anim_image);

达成:

 ViewGroup mainLayout = (ViewGroup) findViewById(R.id.main);
    v = (ViewGroup) getLayoutInflater().inflate(R.layout.image_layout, mainLayout, false);
    mainLayout.addView(v);

    final ImageView backgroundOne = (ImageView) v.findViewById(R.id.anim_image);

    final ValueAnimator animator = ValueAnimator.ofFloat(1.0f, 0.0f);
    animator.setRepeatCount(ValueAnimator.INFINITE);
    animator.setInterpolator(new LinearInterpolator());
    animator.setDuration(10000L);
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            final float progress = (float) animation.getAnimatedValue();
            final float width = v.getWidth();
            final float translationX = width * progress;
            v.setTranslationX(translationX);
            v.setTranslationX(translationX - width);
        }
    });
    animator.start();