1

我试图在 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();
    }
});

动画开始并运行良好。但是,当单击停止按钮时,应用程序会崩溃,因为“动画”对象似乎为空。

4

4 回答 4

2

使用animation.dismiss()代替animation.cancel();

于 2014-11-20T14:32:09.983 回答
1

该对象ObjectAnimator animation只能在onClick开始按钮的方法中访问。你以后没有参考它。

于 2014-11-20T14:35:14.230 回答
0

这是一个范围问题——你有一个同名的方法局部变量和全局变量。您需要取出另一个声明:

前任:

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();
    }
});
于 2014-11-20T15:08:14.090 回答
0

将您的动画变量初始化移入onCreate并尝试animation.dismiss()单击停止按钮。

public class MainActivity extends Activity{

    ObjectAnimator animation;

    public void onCreate(Bundle icicle) {

    animation = ObjectAnimator.ofFloat(iv, "rotation", 360);
于 2014-11-20T14:42:14.560 回答