0

我有一个扩展 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)

为什么我不能将 Animation 实例上载到我的 CustomAnimation,它扩展了 Animation ?

4

1 回答 1

3

这不是向上倾倒,这是向下倾倒。向上转换的形式CustomAnimation为 to Animation

大概AnimationUtils.loadAnimation会返回对实际上不是CustomAnimationa 的对象的引用,因此您不能对其进行强制转换。只有在执行时对象的实际类型与您要转换的类型兼容时,您才能转换为一个类型。例如:

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

Object a = "Foo";
String b = (String) a; // This is fine
于 2012-06-21T07:09:11.253 回答