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

3

我的视图包含一组普通的小部件和一个SurfaceView。我不知道为什么在获取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
        }

当我查看 Android 文档中的 `getSurface()` 方法时,文档如下所示:
`getSurface()` 方法可以直接访问 surface 对象。然而,surface 并不总是可用的。例如,在使用 SurfaceView 时,只有当视图已经附加到窗口管理器并执行了布局以确定 Surface 的尺寸和屏幕位置后,holder 的 Surface 才会被创建。因此,通常需要实现 `Callback.surfaceCreated` 方法来判断何时 Surface 可供使用。
我知道我可能错过了某些东西,但我不太理解这段话。请为我解释一下,并告诉我 `Callback.surfaceCreated` 是什么意思,以及如何实现它?
谢谢 :)
2个回答

13
您正在尝试在表面尚未可用时使用它。 这没关系,在您的 Activity.onCreateActivity.onResume 方法中,实际上表面位于 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());

0

我找到了解决方案,这对我起作用了。实际上错误在于选择正确的尺寸,因此在使用MediaRecorder.setVideoSize()时,请使用此方法选择最佳尺寸。

private static Size chooseOptimalSize(Size[] choices, int width, int height) {
        Size bigEnough = null;
        int minAreaDiff = Integer.MAX_VALUE;
        for (Size option : choices) {
            int diff = (width*height)-(option.getWidth()*option.getHeight()) ;
            if (diff >=0 && diff < minAreaDiff &&
                    option.getWidth() <= width &&
                    option.getHeight() <= height) {
                minAreaDiff = diff;
                bigEnough = option;
            }
        }
        if (bigEnough != null) {
            return bigEnough;
        } else {
            Arrays.sort(choices,new CompareSizeByArea());
            return choices[0];
        }

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接