2017-08-15 112 views
1

我引用了其他问题,但找不到解决方案,也是编程方面的新手。如何将ImageView永久设置在TranslateAnimation后的某个位置

所以我在我的ImageView上实现了一个TranslateAnimation,但是一旦动画结束,它就会返回到原来的位置。我使用Override onAnimationEnd,但似乎没有工作。有人可以弄清楚我应该做什么?

public class PackAnimation extends AppCompatActivity { 

    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.pack_animation); 
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 

    String s = getIntent().getStringExtra("CHOICE"); 


    final ImageView pandya = (ImageView) findViewById(R.id.pandya); 

    final int amountToMoveRight = 600; 
    final int amountToMoveDown = 0; 

    TranslateAnimation anim = new TranslateAnimation(0, amountToMoveRight, 0, amountToMoveDown); 
    anim.setDuration(100); 

    anim.setAnimationListener(new TranslateAnimation.AnimationListener() { 

     @Override 
     public void onAnimationStart(Animation animation) { } 

     @Override 
     public void onAnimationRepeat(Animation animation) { } 

     @Override 
     public void onAnimationEnd(Animation animation) 
     { 
      RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)pandya.getLayoutParams(); 
      params.topMargin += amountToMoveDown; 
      params.leftMargin += amountToMoveRight; 
      pandya.setLayoutParams(params); 
     } 
    }); 

    pandya.startAnimation(anim); 
} 

} 

回答

0

您可以使用anim.setFillAfter(true)TranslateAnimation并获得按钮停留在新的位置,但点击按钮不会在新的岗位工作。因此使用ViewPropertyAnimatorObjectAnimator。这些属性动画会改变View的位置,而TranslateAnimation是查看动画,并且不会更改视图的实际属性。

例如,使用ViewPropertyAnimator

pandya.animate() 
    .translationX(amountToMoveRight) 
    .translationY(amountToMoveDown); 

请参考blog更多信息:

最后,以前的动画改变 目标对象的视觉外观...但他们没实际上并不是自己改变对象 。你可能遇到过这个问题。假设你想 将一个按钮从屏幕的一侧移动到另一侧。 您可以使用一个 TranslateAnimation来完成此操作,并且该按钮将会愉快地沿着 滑动到屏幕的另一侧。 动画完成后, 会很高兴地回到原来的位置。因此,您在Animation上找到 setFillAfter(true)方法并再次尝试。这一次, 按钮保留在动画所在的位置。和 你可以通过点击来验证 - 嘿!如何按钮不是 点击?问题在于动画更改了绘制按钮 的位置,但不是容器中实际存在按钮的位置。如果你想点击按钮,你必须点击 它曾经居住的位置。或者,作为一个更有效的解决方案 (对用户来说只是一个更有用的东西),你会有编写 您的代码在动画完成时实际更改布局 中按钮的位置。

+0

嘿非常感谢提及ViewPropertyAnimator,在我工作的上下文中,我认为这是最好的方法。 –

+0

乐意帮忙。 :) – Bob

0

使用anim.setFillAfter(true);它将在动画结束后保持在最终位置。