SurfaceView、GLSurfaceView和FrameLayout的区别及用法

9

我是一个新手,对Java和OpenGL不太熟悉。

我正在尝试获取相机预览屏幕,并能同时显示3D对象。我已经查看了API演示中的示例,并尝试将其代码组合起来,但似乎并没有起作用。启动时会强制关闭,并报告空指针异常错误。请问有人能告诉我出了什么问题,以及如何解决?我组合代码的方式如下:

myoverview.xml


<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <android.opengl.GLSurfaceView 
            android:id="@+id/cubes" 
            android:orientation="horizontal" 
            android:layout_width="fill_parent" 
            android:layout_height="fill_parent"/> 
    <SurfaceView 
            android:id="@+id/camera" 
            android:layout_width="fill_parent" 
            android:layout_height="fill_parent"/> 
</FrameLayout>

myoverview.java


import android.app.Activity; 
import android.os.Bundle; 
import android.view.SurfaceView; 
import android.view.Window; 
public class MyOverView extends Activity { 
@Override 
    protected void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       // Hide the window title. 
       requestWindowFeature(Window.FEATURE_NO_TITLE); 
       // camera view as the background 
       SurfaceView cameraView = (SurfaceView) findViewById(R.id.camera); 
       cameraView = new CameraView(this); 
       // visual of both cubes 
       GLSurfaceView cubesView = (GLSurfaceView) findViewById(R.id.cubes); 
       cubesView = new GLSurfaceView(this); 
       cubesView.setRenderer(new CubeRenderer(false)); 
       // set view 
       setContentView(R.layout.myoverview); 
    } 
}

GLSurfaceView.java


import android.content.Context; 
class GLSurfaceView extends android.opengl.GLSurfaceView { 
    public GLSurfaceView(Context context) { 
            super(context); 
    } 
} 

注意:

  • 由于它们只是api演示的副本,因此我没有列出其余的文件。cameraView是指camerapreview.java示例,CubeRenderer是指CubeRenderer.java和Cube.java示例。任何帮助都将不胜感激。

  • 抱歉,由于格式错误,我没有意识到编码不正确。

4个回答

4
这其实很简单...如果你想在XML中定义你的视图,只需实现:
Public GLSurfaceView(Context context, AttributeSet attrs) {
...
super(context, attrs);
}

使用GLSurfaceView(Context context)的替代方案

当视图从XML初始化时,这个方法会自动调用。我也遇到了同样的问题,并通过这种方式解决了它。


4
当你在处理 .xml 文件时遇到空指针异常的原因是因为你实际上在 Java 代码中创建了新的视图,而不是使用可能已经传递属性的 .xml 文件中的视图。新的视图显然会具有空值,从而引发空指针异常。例如,如果你已经在包含 FrameLayout 的 .xml 文件中创建了视图,则不需要在代码中创建 cubesView = new GLSurfaceView(this)。请注意保留 HTML 标记。

1
找到了解决方法...通过Java的方式...只需使用addContentView而不是使用xml...好吧,至少问题解决了。 :)

0

我在这个SO链接中实际上已经完成了这个,它提供了完整的实现。


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