java:将动画向上转换为CustomAnimation时的ClassCastException

时间:2012-06-21 07:03:54

标签: java android android-animation classcastexception

我有一个扩展android.view.Animation的类:

package diffusi.on.com.fifteen_puzzle;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

public class CustomAnimation extends Animation {

    private boolean _isLast = false;

    private View _currentTarget = null;

    public interface AnimationListener {
        void onAnimationEnd(CustomAnimation animation);
        void onAnimationRepeat(CustomAnimation animation);
        void onAnimationStart(CustomAnimation animation);
    }

    public static void animateSetOfViews(
            View[] viewsSet, 
            int animResId, 
            int[] startTimeOffsets,
            Context context,
            AnimationListener animationListener
        ) {
        CustomAnimation animation;
        int startTimeOffset; 
        boolean isLastAnim;

        for (int intA = 0; intA < viewsSet.length; intA++) {
            isLastAnim = intA == viewsSet.length - 1;
            animation = (CustomAnimation) AnimationUtils.loadAnimation(context, animResId);
            if (intA <= startTimeOffsets.length - 1) {
                startTimeOffset = startTimeOffsets[intA];
            } else startTimeOffset = 0;
            animation.applyToView(viewsSet[intA], startTimeOffset, isLastAnim, animationListener);
        }
    }

    public CustomAnimation() {

    }

    public CustomAnimation(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    public boolean isLast() {
        return this._isLast;
    }

    public View getCurrentTarget() {
        return this._currentTarget;
    }

    private void applyToView(View view, int startTimeOffset, boolean isLast, AnimationListener listener) {
        this._isLast = isLast;
        this._currentTarget = view;
        this.setStartOffset(startTimeOffset);
        this.setAnimationListener((Animation.AnimationListener) listener);
        this._currentTarget.startAnimation(this);
    }

}

它在IDE中编译没有错误。但是在runtame中,它会在线引发异常(ClassCastEcxeption): animation =(CustomAnimation)AnimationUtils.loadAnimation(context,animResId)

为什么我无法将动画实例向上转换为我的CustomAnimation,它扩展了动画?

1 个答案:

答案 0 :(得分:3)

它不是向上转播,它是向下转播。向上转换的格式为CustomAnimationAnimation

大概AnimationUtils.loadAnimation会返回对不是实际上是CustomAnimation的对象的引用 - 所以你不能强制转换它。当执行时对象的实际类型与您要转换的类型兼容时,只能转换为类型。例如:

Object x = new Integer(10);
String y = (String) x; // Bang - invalid cast

Object a = "Foo";
String b = (String) a; // This is fine