0

I have an ImageView located in a relative layout. I'm moving the ImageView from the top of the screen to the bottom by using a Timer. Below is the code of the timer

timer.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            public void run() {

                ObjectAnimator anim= ObjectAnimator.ofFloat(submarine, "translationY", submarine.getTop(), submarine.getTop()+50);
                anim.setDuration(1000);
                submarine.setTop(submarine.getTop()+50);
                    submarine.setBottom(submarine.getBottom()+50);
                //submarine.startAnimation(sub_down);
                anim.start();
            }
        });


    }
}, 0, 3000);

The ImageView is called submarine. The animation works fine but when I change the value of some TexViews in the same RelativeLayout the position of the ImageView is being reset to it's original position. I've also tried using the View animations of Android but the result was the same. Is there any way to avoid the resetting of the submarine ImageView and maintain it's changed position?

mmBs
  • 8,421
  • 6
  • 38
  • 46
Sergios
  • 133
  • 1
  • 1
  • 9

2 Answers2

0

This is the classic behavior of android animation. You must specify what to do at the end of your animation or it will go back to the initial state.

Here a solved question which may help you: Android: Animation Position Resets After Complete

Community
  • 1
  • 1
Al Blanc
  • 38
  • 6
0

I'm using an objectanimator which is supposed to keep the position of the object at the end of the animation. The only thing that worked was setting the margins of the view at the end of the animation as you can see in the code below:

@Override
        public void onAnimationEnd(Animation animation) {
            runOnUiThread(new Runnable() {
                public void run() {
                    submarine.clearAnimation();
                    LayoutParams lp = new LayoutParams(submarine.getWidth(), submarine.getHeight());
                    lp.setMargins(submarine.getLeft(), submarine.getTop()+50, 0, 0);
                    submarine.setLayoutParams(lp);
                }
            });

If you try positioning the item by using the setTop and setLeft the view will reset to it's original position. Another note is that you need to run the clearAnimation method of the view before positioning it otherwise the view will flicker when the animation ends.

Sergios
  • 133
  • 1
  • 1
  • 9