ImageView上的TranslateAnimation(Android)

时间:2012-10-19 23:16:32

标签: android position imageview android-animation translate-animation

所以我的布局中有一个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的替代方法?

感谢您提供的任何帮助。 :)

1 个答案:

答案 0 :(得分:13)

好的,所以我一路走来。我现在使用全局变量,每当我为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);

希望如果您遇到同样的问题,这会有所帮助。我已经看过几个这样的帖子,没有好的答案。

相关问题