So I have an ImageView in my layout and I wanted to slide it to the right or left when the user swipe over the latter. I used TranslateAnimation to translate the ImageView, as shown below.
ImageView logoFocus = (ImageView) findViewById(R.id.logoFocus);
Animation animSurprise2Movement = new TranslateAnimation(logoFocus.getLeft(), logoFocus.getLeft()+150, logoFocus.getTop(), logoFocus.getTop());
animSurprise2Movement.setDuration(1000);
animSurprise2Movement.setFillAfter(true);
animSurprise2Movement.setFillEnabled(true);
logoFocus.startAnimation(animSurprise2Movement);
I've placed this code in my Swipe Right section, and the same code but using getLeft()-150 for the Swipe Left section. It works as expected when I swipe a first time, but when I swipe to the other direction, the ImageView goes back to its original position, then slides in the other direction, instead of only sliding to the original position.
I've already tried to add the following in the onAnimationEnd method of an AnimationListener which I've set to the Animation, but in vain.
MarginLayoutParams params = (MarginLayoutParams) logoFocus.getLayoutParams();
params.setMargins(logoFocus.getLeft()+150, logoFocus.getTop(), logoFocus.getRight(), logoFocus.getBottom());
logoFocus.setLayoutParams(params);
I've also tried the following in the same method, but that neither didn't work as expected.
((RelativeLayout.LayoutParams) logoFocus.getLayoutParams()).leftMargin += 150;
logoFocus.requestLayout();
Would anyone please help me? The position doesn't seem to change after the Animation, even with setFillAfter(true) and setFillEnabled(true) used. Is there an alternative to using TranslateAnimation?
Thank you for any help I can get. :)
Okay, so I worked my way around it. I'm using a global variable now which I update each time I animate the ImageView, instead of trying to force the ImageView to change its actual position. Since I'm using setFillAfter(true) and setFillEnabled(true), it doesn't go back unintentionally to its original position anymore.
private float xCurrentPos, yCurrentPos;
private ImageView logoFocus;
logoFocus = (ImageView) findViewById(R.id.logoFocus);
xCurrentPos = logoFocus.getLeft();
yCurrentPos = logoFocus.getTop();
Animation anim= new TranslateAnimation(xCurrentPos, xCurrentPos+150, yCurrentPos, yCurrentPos);
anim.setDuration(1000);
anim.setFillAfter(true);
anim.setFillEnabled(true);
animSurprise2Movement.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation arg0) {}
@Override
public void onAnimationRepeat(Animation arg0) {}
@Override
public void onAnimationEnd(Animation arg0) {
xCurrentPos -= 150;
}
});
logoFocus.startAnimation(anim);
Hope this helps if you're having the same problem. I've seen several posts like this with no good answer.