我有一个动画类,当我需要将图像从某个地方移动到另一个地方时,我从主类中调用它......但问题是当我调用它时,它变成了 NullPointerException。这是我的代码:
public class Animation extends Activity{
ImageView image;
int width;
int fromXDelta;
AnimationSet animation = new AnimationSet(true);
TranslateAnimation translateAnimation = null;
Animation(View main) {
image = (ImageView) main.findViewById(R.id.logo);
fromXDelta = image.getLeft();
// this line gives me error:
width = getWindowManager().getDefaultDisplay().getWidth();
}
public void animateToLeft () {
translateAnimation = new TranslateAnimation(0, -fromXDelta, 0, 0);
translateAnimation.setDuration(1000);
animation.addAnimation(translateAnimation);
animation.setAnimationListener(new AnimationListener() {
public void onAnimationEnd(android.view.animation.Animation v) {
// TODO Auto-generated method stub
image.clearAnimation();
v.reset();
image.layout(0, 0, image.getWidth(), image.getHeight());
}
public void onAnimationRepeat(android.view.animation.Animation arg0) { }
public void onAnimationStart(android.view.animation.Animation arg0) { }
});
image.startAnimation(animation);
}
public void animateToRight () {
translateAnimation = new TranslateAnimation(fromXDelta, width - image.getWidth() - fromXDelta , 0, 0);
translateAnimation.setDuration(1000);
animation.addAnimation(translateAnimation);
animation.setAnimationListener(new AnimationListener() {
public void onAnimationEnd(android.view.animation.Animation v) {
// TODO Auto-generated method stub
image.clearAnimation();
v.reset();
image.layout(width - image.getWidth(), 0, width, image.getHeight());
}
public void onAnimationRepeat(android.view.animation.Animation arg0) { }
public void onAnimationStart(android.view.animation.Animation arg0) { }
});
image.startAnimation(animation);
}
public void animateToEx (int control) {
if(control == 0) {
// left to ex point
translateAnimation = new TranslateAnimation(fromXDelta, width - image.getWidth() - fromXDelta , 0, 0);
} else if(control == 2) {
// right to ex point
translateAnimation = new TranslateAnimation(fromXDelta, width - image.getWidth() - fromXDelta , 0, 0);
}
translateAnimation.setDuration(1000);
animation.addAnimation(translateAnimation);
animation.setAnimationListener(new AnimationListener() {
public void onAnimationEnd(android.view.animation.Animation v) {
// TODO Auto-generated method stub
image.clearAnimation();
v.reset();
image.layout(width - image.getWidth(), 0, width, image.getHeight());
}
public void onAnimationRepeat(android.view.animation.Animation arg0) { }
public void onAnimationStart(android.view.animation.Animation arg0) { }
});
image.startAnimation(animation);
}
}
提前致谢。
最佳答案
我认为你做得不对......你需要阅读 Activity 的文档及其生命周期
。您定义的构造函数永远不会调用...使用 onCreate
而不是您的构造函数...
关于android - getWindowManager() 返回 Null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9258541/