繁体   English   中英

Android:holder.getSurface()始终返回null

[英]Android : holder.getSurface() always return null

我的观点是一堆普通的小部件和一个表面视图。 我不知道为什么在我得到surfaceholder SurfaceView和使用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()方法时。 这是怎么说的:

直接访问表面对象。 Surface可能并不总是可用 - 例如,在使用SurfaceView时,在将视图附加到窗口管理器并执行布局以确定Surface的尺寸和屏幕位置之前,不会创建支架的Surface。 因此,您通常需要实现Callback.surfaceCreated以找出Surface何时可用。

我不太了解这一点,但我知道我错过了一些东西。 请解释一下,并告诉我Callback.surfaceCreated意思,以及如何实现它?

谢谢 :)

您正在尝试使用表面尚不可用。 没关系,它在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());

我发现解决方案,这对我有用,感染错误是选择正确的大小,所以使用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];
        }

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM