在Android中以动画方式将ImageView移动到不同位置

Kus*_*hal 23 animation android android-animation

我有几个ImageView在A S RelativeLayout.现在,当用户点击任何ImageView时,我希望将它移动到具有微妙动画的指定位置.

例如; 我最初设置LayoutParamsImageViewas 关联的边距layoutparams1.setMargins(90,70,0,0);,然后将其添加到布局中.

当点击imageview时,我希望它的新位置是200,200动画.

那么,有可能吗?如果有,那怎么样?

请注意,我以编程方式创建了它们的RelativeLayout所有子项ImageView.

而且我是Android开发的新手,所以预计会有一个详尽的答案.

D-3*_*-32 54

TranslateAnimation animation = new TranslateAnimation(0, 50, 0, 100);
animation.setDuration(1000);
animation.setFillAfter(false);
animation.setAnimationListener(new MyAnimationListener());

imageView.startAnimation(animation);
Run Code Online (Sandbox Code Playgroud)

更新: 问题在于它View实际上仍处于旧位置.所以我们必须在动画结束时移动它.要检测动画何时结束,我们必须创建自己的animationListener(在我们的activity类中):

private class MyAnimationListener implements AnimationListener{

    @Override
    public void onAnimationEnd(Animation animation) {
        imageView.clearAnimation();
        LayoutParams lp = new LayoutParams(imageView.getWidth(), imageView.getHeight());
        lp.setMargins(50, 100, 0, 0);
        imageView.setLayoutParams(lp);
    }

    @Override
    public void onAnimationRepeat(Animation animation) {
    }

    @Override
    public void onAnimationStart(Animation animation) {
    }

}
Run Code Online (Sandbox Code Playgroud)

因此,onClickEvent它将在它的新地方再次被解雇.动画现在它移动更加下来,所以你可能想保存xy在一个变量,所以,在onAnimationEnd()你移动它不是一个固定的位置.

  • 作品!!但是在ImageView的新位置,它不响应任何点击事件,而且,如果我点击它的先前位置,相同的imageview的另一个实例动画.有什么办法解决吗? (2认同)

ArM*_*372 10

使用也更好ObjectAnimator.这一观点处于新的位置.例如 :

ImageView splash ;
@Override
public boolean onTouchEvent(MotionEvent event) {
    float tx = event.getX();
    float ty = event.getY();

    int action = event.getAction();
    switch(action) {
        case MotionEvent.ACTION_DOWN:
            tx = event.getX();
            ty = event.getY();

            //       findViewById(R.id.character).setX(tx-45);
            //      findViewById(R.id.character).setY(ty-134);

            ObjectAnimator animX = ObjectAnimator.ofFloat(splash, "x", tx-45);
            ObjectAnimator animY = ObjectAnimator.ofFloat(splash, "y", ty-134);
            AnimatorSet animSetXY = new AnimatorSet();
            animSetXY.playTogether(animX, animY);
            animSetXY.start();

            break;
        default:
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)


Dia*_*ani 6

你可以使用这个代码

imageView.animate().x(80).y(212).setDuration(300);
Run Code Online (Sandbox Code Playgroud)

或者

对于软动画,您可以使用这个库

https://github.com/wirecube/android_additive_animations