动画后为设定图像添加延迟

时间:2016-07-08 14:04:58

标签: android android-animation

我想点击图片,将其旋转180度并更改图片资源。但它似乎无法发挥作用。

public class MainActivity extends AppCompatActivity {

GridLayout gridView;
boolean isGrey = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gridView = (GridLayout) findViewById(R.id.grid);

}

public void flip(final View view){

    ImageView tile = (ImageView) view;
    if(isGrey) {
        tile.animate().rotationXBy(180f).setDuration(700);
        tile.setImageResource(R.drawable.green);
        isGrey = false;
    }else{
        tile.animate().rotationXBy(-180f).setDuration(700);
        tile.setImageResource(R.drawable.grey);
        isGrey = true;
    }
    Log.i("Tag", tile.getTag().toString());

}
}

我想做的就是在动画之后更改setImageResource而不是立即。

1 个答案:

答案 0 :(得分:1)

您可以使用ViewPropertyAnimator的withEndAction(Runnable r)方法。 您的代码应该如下所示:

public class MainActivity extends AppCompatActivity {

GridLayout gridView;
boolean isGrey = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

gridView = (GridLayout) findViewById(R.id.grid);

}

public void flip(final View view){

final ImageView tile = (ImageView) view;
if(isGrey) {
    tile.animate().rotationXBy(180f).setDuration(700).withEndAction(new Runnable() {
        @Override
        public void run() {
    tile.setImageResource(R.drawable.green);
    isGrey = false;
        }
    });
}else{
    tile.animate().rotationXBy(-180f).setDuration(700).withEndAction(new Runnable() {
        @Override
        public void run() {
            tile.setImageResource(R.drawable.grey);
            isGrey = true;
        }
    });
}
Log.i("Tag", tile.getTag().toString());

}
}