当我更改 Android 的屏幕方向时,为什么会在画布上出现空指针异常?
我的程序在以任何旋转/方向启动时都运行得很好,但是当我在运行时更改横向<->纵向之间的方向时,由于我的画布,我得到一个空指针异常。
@Override
public void run(){
while(running){
if(surfaceHolder.getSurface().isValid()){
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK); //NULLPOINTEREXCEPTION here
paint(canvas); //another function of mine
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
我的清单中有 android:configChanges="orientation" 以及
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
}
当我注释掉 canvas.drawColor(Color.BLACK) 时,调用 Paint(canvas) ,然后在下次使用 canvas 时发生空指针异常功能。
帮助?
My program runs perfectly well when starting in any rotation/orientation, but when I change the orientation between landscape<->portrait while it's running, I get a null pointer exception because of my canvas.
@Override
public void run(){
while(running){
if(surfaceHolder.getSurface().isValid()){
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK); //NULLPOINTEREXCEPTION here
paint(canvas); //another function of mine
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
And I have android:configChanges="orientation" in my manifest as well as
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
}
When I comment out canvas.drawColor(Color.BLACK), paint(canvas) gets called and then the null pointer exception happens the next time canvas is used in that function.
Help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SurfaceHolder 的 Javadoc 表示
如果
将返回Canvas
尚未准备好,lockCanvas()null
,因此您需要为此做好准备。它表示使用Callback.surfaceCreated()
回调来了解何时可以安全地使用Canvas
。The Javadoc for SurfaceHolder says that
lockCanvas()
will returnnull
if theCanvas
is not ready yet, so you need to be prepared for that. It says to use theCallback.surfaceCreated()
callback to know when it's safe to use theCanvas
.我建议看一下这个线程:
Activity 在旋转 Android 上重新启动
具体来说:
创建一个应用程序类并将画布初始化移动到那里。
I would recommend taking a look at this thread:
Activity restart on rotation Android
specifically:
creating an Application class and moving the canvas initialization there.