【问题标题】:TranslateAnimation on ImageView (Android)ImageView 上的 TranslateAnimation (Android)
【发布时间】:2012-10-10 14:59:41
【问题描述】:

所以我的布局中有一个 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);

我已将此代码放在我的 Swipe Right 部分中,相同的代码但使用 getLeft()-150 用于 Swipe Left 部分。当我第一次滑动时,它按预期工作,但是当我向另一个方向滑动时,ImageView 会回到原来的位置,然后向另一个方向滑动,而不是只滑动到原来的位置。

我已经尝试在已设置为 Animation 的 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 的替代方法?

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

【问题讨论】:

  • 是的,您遇到了 TranslateAnimation API 的设计限制。动画改变了 ImageView 在屏幕上的呈现位置,但它实际上并没有改变 ImageView 在布局中的位置。另一种方法是使用 Android 3.0 (android-developers.blogspot.com/2011/02/…) 引入的新的基于对象的动画 API
  • 感谢您的回复。但是,如果我正在为 Android 2.3(API 级别 9)进行开发,它就无法正常工作了?有没有别的办法..? ://
  • 我认为您可以手动移动该项目,只是您没有找到正确的方法。尝试在 ImageView 上设置一个全新的 LayoutParams,而不是更新当前的。哎呀-抱歉,我错过了您尝试过的代码。请放心,可以通过编程方式在布局中移动 ImageView - 也许其他人可以发现您代码中的故障。

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


【解决方案1】:

好的,所以我解决了这个问题。我现在使用一个全局变量,每次我为 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);

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

【讨论】:

    猜你喜欢
    • 2012-01-17
    • 2011-09-27
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    相关资源
    最近更新 更多