Android : holder. getSurface() 总是返回 null

标签 android android-layout surfaceview surfaceholder

我的 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.onCreateActivity.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/

相关文章:

android - EditText.setError() 的弹出消息布局看起来很奇怪

android - 为什么 Android Studio 设计器显示我的自定义 View 嵌套在自身内部,而它不是

android - 图像未在 "onTouch"方法中显示

Android - 相机应用程序通过了空表面

android - 在 Android 中保护您的 api key

android - 如何在Android Studio中禁用丢失的'@override'注释检查

android - 布局中的三角形 - Android UI

android - 安卓播放时视频旋转90度怎么解决?

android - SeekBar DataBinding 表达式上的资源 NotFoundException

android - 使用 Parcelable 将 List<Object> 保存到实例状态