所以我的布局中有一个 ImageView,我想在用户滑过后者时将它向右或向左滑动。我使用 TranslateAnimation 来翻译 ImageView,如下所示。
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);
我已将这段代码放在我的向右滑动部分,同样的代码,但对向左滑动部分使用了 getLeft()-150。当我第一次滑动时它按预期工作,但是当我向另一个方向滑动时,ImageView 回到其原始位置,然后向另一个方向滑动,而不是仅滑动到原始位置。
我已经尝试在我已设置为动画的 AnimationListener 的 onAnimationEnd 方法中添加以下内容,但没有成功。
MarginLayoutParams params = (MarginLayoutParams) logoFocus.getLayoutParams();
params.setMargins(logoFocus.getLeft()+150, logoFocus.getTop(), logoFocus.getRight(), logoFocus.getBottom());
logoFocus.setLayoutParams(params);
我也用相同的方法尝试了以下方法,但都没有按预期工作。
((RelativeLayout.LayoutParams) logoFocus.getLayoutParams()).leftMargin += 150;
logoFocus.requestLayout();
谁能帮帮我?即使使用了 setFillAfter(true) 和 setFillEnabled(true),在动画之后位置似乎没有改变。有没有使用 TranslateAnimation 的替代方法?
感谢您提供的任何帮助。 :)
最佳答案
好的,所以我解决了这个问题。我现在正在使用一个全局变量,每次我为 ImageView 设置动画时都会更新它,而不是试图强制 ImageView 更改其实际位置。由于我使用了 setFillAfter(true) 和 setFillEnabled(true),它不会再无意中回到原来的位置。
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);
如果您遇到同样的问题,希望这对您有所帮助。我看过几个这样的帖子,但都没有很好的答案。
关于android - ImageView 上的 TranslateAnimation (Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12983681/