2014-11-14 126 views
1

我试图运行Android样品http://developer.android.com/training/graphics/opengl/index.html添加GLSurfaceView布局

我必须添加一些控件,如文本和按钮的观点,这将看起来像android ui

如何在Android的布局中使用GLSurfaceView?

主要活动(跳过一些自动生成的代码)

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    mGLSurfaceView = (myGLSurfaceView) findViewById(R.id.glSurfaceViewID); //crashes 
} 

表面视图

public class myGLSurfaceView extends GLSurfaceView { 
private myRenderer mRenderer; 

@Override 
public boolean onTouchEvent(MotionEvent event) { 
    // TODO Auto-generated method stub 
    return super.onTouchEvent(event); 
} 

public myGLSurfaceView (Context context) { 
    super(context); 
    // Create an OpenGL ES 2.0 context. 
    setEGLContextClientVersion(2); 


    // Creating a Renderer 
    setRenderer(new myRenderer(context));  

    // Render the view only when there is a change in the drawing data 
    setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); 
} 

public myGLSurfaceView (Context context, AttributeSet attrs) { 
    super(context, attrs); 
    // TODO Auto-generated constructor stub 
} 

public void setRenderer(myRenderer mRenderer, float density) { 
    // TODO Auto-generated method stub 

} 

} 

布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:id= "@+id/linearlayout1" > 

<Button 
    android:id="@+id/buttonID" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginTop="10dip" 
    android:text="A Button" /> 

<GLSurfaceView 
    android:id="@+id/glSurfaceViewID" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_weight="0.23" /> 

回答

2

GLSurfaceView与将其添加到布局时没有任何不同。唯一的考虑是它在使用时大部分都是子类,就像它在你的代码中完成的那样,而对其他类型的视图来说这不是很常见(但也不是非常不寻常)。

在你尝试的问题是将它添加到布局时使用的类名:

<GLSurfaceView 
    ... 

毫不奇怪,当布局膨胀,这将创建GLSurfaceView类的一个实例。但那不是你想要的。您想要创建派生类的实例,即myGLSurfaceView。一个明显的尝试做到这一点将是:

<myGLSurfaceView 
    ... 

这是不行的。类名称需要用包名称限定。说你myGLSurfaceView类是com.msl.myglexample包的一部分:

package com.msl.myglexample; 

public class myGLSurfaceView extends GLSurfaceView { 
    ... 
} 

然后在布局文件的功能项将是:

<com.msl.myglexample.myGLSurfaceView 
    .... 

这不是在OP的代码中的问题,但因为这是人们在尝试这样做时遇到的常见问题:衍生GLSurfaceView的构造函数以AttributeSet作为参数也很重要。这对于所有从XML充值的视图都是必需的。

public myGLSurfaceView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
}