我有一个动画类,当我需要将图像从某个地方移动到另一个时,我正在从主类调用它...但事情就是当我调用它时,它会变成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);
}
}
提前致谢。
答案 0 :(得分:2)
我认为你做得不对......你需要阅读Activity及其life cycle
的文档。你定义的构造函数永远不会调用...使用onCreate
而不是你的构造函数......
答案 1 :(得分:0)
显然该方法已被弃用,请尝试使用此方法
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
答案 2 :(得分:0)
您是否尝试过使用getSystemService()?
getSystemService(Context.WINDOW_SERVICE);