我的 View 是一堆普通的小部件和一个表面 View 。不知道为什么获取到SurfaceView的surfaceholder
后,在holder上再次使用getSurface()
,总是返回null。
这是我的示例代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
}
@Override
public void onResume() {
super.onResume();
surface = (SurfaceView) findViewById(R.id.surfaceView);
this.holder = surface.getHolder();
if (holder.getSurface().isValid()){ // get surface again
Log.i("Notice","Surface holder is valid");
}
else
Log.i("Notice","Surface holder ISNOT valid"); //Always receive this
}
当我看到 getSurface()
方法的 Android 文档时。它是这样说的:
Direct access to the surface object. The Surface may not always be available -- for example when using a SurfaceView the holder's Surface is not created until the view has been attached to the window manager and performed a layout in order to determine the dimensions and screen position of the Surface. You will thus usually need to implement Callback.surfaceCreated to find out when the Surface is available for use.
我不太明白这一点,但我知道我错过了一些东西。请帮我解释一下,告诉我Callback.surfaceCreated
的意思,以及如何实现?
谢谢:)
最佳答案
您正在尝试使用尚不可用的表面。没关系,它在您的 Activity.onCreate
或 Activity.onResume
方法中不可用,因为实际上 surface 放置在 Activity 窗口后面的单独窗口中,并且有自己的生命周期。
您需要实现 SurfaceHolder.Callback接收有关 Surface
可用性的事件并从单独的线程中绘制。查看 Android SDK 示例文件夹中的 LunarLander 项目,其中显示了如何正确使用 SurfaceView。
你的回调看起来像这样:
public class MyCallback implements SurfaceHolder.Callback {
@Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// you need to start your drawing thread here
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// and here you need to stop it
}
}
然后您需要将此回调设置为 SurfaceHolder:
surface.getHolder().addCallback(new MyCallback());
关于Android : holder. getSurface() 总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11490711/