此代码在MainActivity中正常工作,但我想将一些动画方法放在不同的类中,并从那里调用它,但我有一个错误 我想了解,为什么它会给我一个错误 任何想法?
public class AnimationClass extends MainActivity{
private static ImageButton heart_icon,bee_icon;
private static int kill_flag = 0;
private static Animation anim_heart, anim_bee;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
heart_icon=(ImageButton)findViewById(R.id.heart_icon);
bee_icon = (ImageButton)findViewById(R.id.bee_icon);
}
public static void loadAnimations(Activity activity){
anim_heart = AnimationUtils.loadAnimation(activity, R.anim.heart_anim);
heart_icon.startAnimation(anim_heart);
anim_bee = AnimationUtils.loadAnimation(activity, R.anim.bee_anim);
bee_icon.startAnimation(anim_bee);
}
}
动画:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:shareInterpolator="true">
<scale
android:fillAfter="true"
android:repeatCount="infinite"
android:repeatMode="reverse"
android:duration="1000"
android:fromXScale="1.0"
android:toXScale="1.2"
android:fromYScale="1.0"
android:toYScale="1.2"
android:pivotX="50%"
android:pivotY="50%"/>
<rotate
android:fillAfter="true"
android:repeatCount="infinite"
android:repeatMode="reverse"
android:duration="1200"
android:fromDegrees="-20"
android:toDegrees="15"
android:pivotX="80%"
android:pivotY="20%"/>
<translate
android:fillAfter="true"
android:repeatCount="infinite"
android:repeatMode="reverse"
android:duration="800"
android:toXDelta="5"
android:toYDelta="-5"/>
<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:duration="1500"/>
</set>
错误:anim_heart = AnimationUtils.loadAnimation(activity, R.anim.heart_anim);
答案 0 :(得分:1)
您似乎误解了静态变量和方法的工作原理。
创建AnimationClass
的对象时:
new AnimationClass()
onCreate
被调用,两个ImageButtons
设置正确。
但是,当您调用静态方法loadAnimations
时,ImageButton变量可能仍然为null,而这将返回NPE。
不同的解决方案:
检查空变量:
public static void loadAnimations(Activity activity){
anim_heart = AnimationUtils.loadAnimation(activity, R.anim.heart_anim);
if (heart_icon != null) {
heart_icon.startAnimation(anim_heart);
}
anim_bee = AnimationUtils.loadAnimation(activity, R.anim.bee_anim);
if (bee_icon != null) {
bee_icon.startAnimation(anim_bee);
}
}
如果您作为[{1}}参数传递的活动包含相关视图,您可能希望在现场找到它们:
loadAnimations