2

所以我在我的布局中有一个ImageView,并且我想在用户滑过后者时将其滑动到右侧或左侧。我使用TranslateAnimation来翻译ImageView,如下所示。对ImageView(Android)的TranslateAnimation

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),位置在Animation之后似乎也不会改变。是否有使用TranslateAnimation的替代方法?

谢谢你的帮助,我可以得到。 :)

+1

是的,你已经遇到了TranslateAnimation API的设计限制。动画更改ImageView在屏幕上呈现的位置,但实际上它并不会更改布局中ImageView的位置。另一种方法是使用Android 3.0引入的新的基于对象的动画API(http://android-developers.blogspot.com/2011/02/animation-in-honeycomb.html) – mportuesisf

+0

谢谢您的回应。但是如果我正在开发Android 2.3(API级别9),那么它将无法正确工作?有没有其他的方式..? :/ – jpmastermind

+0

我认为你可以手动移动这个物品,但是你没有找到正确的方法。尝试在ImageView上设置一个全新的LayoutParams,而不是更新当前的一个。糟糕 - 抱歉,我错过了您尝试过的代码。请放心,可以通过编程方式在布局中移动ImageView - 也许另一个人可以发现代码中的故障。 – mportuesisf

回答

11

好吧,所以我按照我的方式工作。我现在正在使用一个全局变量,我每次更新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); 

希望这有助于如果你有同样的问题。我看过几篇这样的帖子,没有很好的答案。