【问题标题】:Animate ImageView on button clicked单击按钮上的动画 ImageView
【发布时间】:2013-01-02 16:54:10
【问题描述】:

我正在尝试翻译 ImageView,每次单击时将其向下移动一步。但是,动画仅适用于第一次单击按钮;所有后续点击只会更改 ImageView 的位置,而不会更改动画。

这是我的 move_down.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<translate 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0%"
    android:toYDelta="100%"
    android:duration="500"
/>

这是我在 main.xml 中的按钮声明:

<Button
     android:id="@+id/bGo"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Go"
 android:onClick="startAnimation" />

这是我的 startAnimation 函数:

public void startAnimation(View view) {
        Animation test = AnimationUtils.loadAnimation(this, R.anim.move_down);
        character.startAnimation(test);//This is the ImageView I'm trying to animate
        test.setAnimationListener(new AnimationListener() {
            public void onAnimationStart(Animation animation) {}
            public void onAnimationRepeat(Animation animation) {}
            public void onAnimationEnd(Animation animation) {
                character.setY(character.getY() + character.getHeight());          
                }
        });     
}

当我注释掉这一行时

character.setY(character.getY() + character.getHeight());

动画会起作用,但 ImageView 的位置会在动画完成后快速恢复。

【问题讨论】:

    标签: android animation android-animation android-imageview


    【解决方案1】:

    取出

    character.setY(character.getY() + character.getHeight());
    

    使用 Animation 的 fillAfter 属性使其停留在动画结束时的位置。

    像这样:

    Animation test = AnimationUtils.loadAnimation(this, R.anim.move_down);
    test.setFillAfter(true);
    

    【讨论】:

    • 这几乎奏效了。当我第二次按下按钮时,ImageView 会弹回原来的位置,而不是向下移动一步。
    【解决方案2】:

    也许你应该尝试这样的事情

    public void startAnimation(View view) 
    {
        Animation test = AnimationUtils.loadAnimation(this, R.anim.move_down);
        character.startAnimation(test);
        character.setVisibility(View.GONE);//when returns to original position, make it invisible
        character.setY(character.getY() + character.getHeight());//move to new location
        character.setVisibility(View.VISIBLE);//make it visible
    }
    

    动画结束后,它会回到原来的位置,所以你需要让它不可见,然后将它移动到动画中它移动到的新位置,然后让它可见。运行时,它应该看起来是无缝的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多