我试图在Button onClick事件上无限期地动画(旋转)一个ImageView,然后在另一个按钮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();
}
});
动画启动并运行正常。然而,当点击停止按钮作为动画时,应用程序崩溃了。对象似乎为空。
答案 0 :(得分:2)
使用animation.dismiss()
代替animation.cancel();
答案 1 :(得分:1)
对象ObjectAnimator animation
只能在onClick
方法中用于启动按钮。你以后没有引用它。
答案 2 :(得分:0)
在onCreate
中移动动画变量初始化,并在点击停止按钮时尝试animation.dismiss()
。
public class MainActivity extends Activity{
ObjectAnimator animation;
public void onCreate(Bundle icicle) {
animation = ObjectAnimator.ofFloat(iv, "rotation", 360);
答案 3 :(得分:0)
这是范围问题 - 您有一个方法局部变量和具有相同名称的全局变量。你需要拿出另一个宣言:
EX:
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);
//remove declaration here so it uses the globally scoped variable
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
if(animation != null) //you'll probably wana do a null check
animation.cancel();
}
});