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); 

希望這有助於如果你有同樣的問題。我看過幾篇這樣的帖子,沒有很好的答案。