我试图在 Button onClick 事件上无限期地为 ImageView 设置动画(旋转),然后在另一个 Button onClick 上停止它。这是我的代码...
public class MainActivity extends Activity{
ObjectAnimator animation;
public void onCreate(Bundle icicle) {
...
Button start = (Button) findViewById(R.id.startbutton);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ImageView iv = (ImageView) findViewById(R.id.wheel);
ObjectAnimator animation = ObjectAnimator.ofFloat(iv, "rotation", 360);
animation.setInterpolator(null);
animation.setRepeatCount(animation.INFINITE);
animation.setDuration(1000);
animation.start();
Log.i(TAG, String.valueOf(animation)); // returns the animation object
}
});
Button stop = (Button) findViewById(R.id.stopbutton);
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, String.valueOf(animation)); // returns null
animation.cancel();
}
});
动画开始并运行良好。但是,当单击停止按钮时,应用程序会崩溃,因为“动画”对象似乎为空。