6

我启动了一个 Android OpenGL 应用程序,我有以下类:

class A extends Activity
class B extends GlSurfaceView implements Renderer

当调用 A 类的 onCreate 时,它​​会创建一个 B 类类型的对象并调用:

setContentView(Bobject)

到目前为止它有效,我花了几天时间。

现在我想向我的应用程序添加按钮并找到 SurfaceViewOverlay 示例。它使用一些 XML 来创建视图层次结构。我想创建一些与我简单地剪切和粘贴 XML 代码非常相似的东西:

    <android.opengl.GLSurfaceView android:id="@+id/glsurfaceview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    <LinearLayout android:id="@+id/hidecontainer"
            android:orientation="vertical"
            android:visibility="gone"
            android:background="@drawable/translucent_background"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            ...

现在记住我原来的类层次结构,我将如何初始化我的视图?我应该在 A 类的 onCreate() 中写什么?

我尝试使用:

Bobject = new B(this);
GLSurfaceView glSurfaceView =
        (GLSurfaceView) findViewById(R.id.glsurfaceview);
    glSurfaceView.setRenderer(Bobject);

它确实在屏幕上绘制了按钮和 GL 视图,但 GL 视图无法接收来自点击/点击的任何输入。

这可能是因为 Bobject 的 onTouchEvent() 没有被调用,因为它仅用作:

Renderer

而不是:

glSurfaceView

目的。

而不是上面的代码,我真正想要的是让 Bobject 替换 glSurfaceView。但我不知道该怎么做。当我确实 findViewById() 时,似乎现在已经创建了 glSurfaceView。我如何要求它为 GL 视图使用 B 类型的对象?

对不起任何新手的错误。对 Android 来说是全新的。

编辑:我也试过这个:

我还尝试了以下方法:在我的 XML 文件中,我将 GLSurfaceView 更改为:

<com.bla.bla.B
            android:id="@+id/glsurfaceview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

在我的 A 类构造函数中,我正在调用:

// This returns null
Bobject = (B) findViewById(R.id.glsurfaceview);

// And this suspends the application. :(
setContentView(R.layout.surface_view_overlay);

我应该如何在我的 XML 文件/活动中使用扩展 glSurfaceView 的自定义类?

4

2 回答 2

7

好的,所以这样做的正确方法是在 B 类中有一个构造函数,它接受:

B(Context context, AttributeSet attrs)
{
  super(context, attrs);
}

在 XML 布局中,使用这个:

<com.bla.bla.B
        android:id="@+id/glsurfaceview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

我的代码中缺少的是构造函数签名。

于 2010-11-08T06:16:08.180 回答
1

解决此问题的另一种方法是将您的视图附加到 Activity A。因此,您使用 setContentView(A object) 而不是使用 setContentView(A object),并且在“A XML”文件中是 GLsurfaceView 视图:

<android.opengl.GLSurfaceView android:id="@+id/glsurfaceview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

然后,您可以在 Activity A 中引用您的 B 对象,因为当您将 ContentView 设置为 A 而不是 B 时,它被夸大了:

GLSurfaceView glSurfaceView = (GLSurfaceView) findViewById(R.id.glsurfaceview);


glSurfaceView.setRenderer();  //no longer have to pass the object

老实说,我不确定如何让它完全按照你想要的方式工作,但在你的情况下,我不确定它最终会有所作为。再说一次,我还是个新手。我有兴趣了解如何以另一种方式做到这一点,因为我今天问了一个类似的问题。

于 2010-11-08T01:48:31.350 回答