我对 Android 和 OpenGL ES 还很陌生。我必须在 OpenGL 中创建一个 GUI,我想将它用作主要 Activity 中的 Fragment
。为了学习如何做到这一点,我尝试了 2 个教程 - this Fragment tutorial和 the Android developer tutorial on OpenGL ES .
但我仍然不明白如何在 Fragment
中包含一个 OpenGL View 。 OpenGL 不使用 XML 布局文件,所以这个过程让我很困惑。我想做这样的事情:在 Fragment
教程的主要 Activity 中,我想用 OpenGL 包含第三个 Fragment
。对我放轻松,我是初学者 :)
最佳答案
如果开发人员教程可以作为引用,那么以下设置将起作用:
Activity :
public class MainActivity extends FragmentActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener()
{
public void onBackStackChanged()
{
int backCount = getSupportFragmentManager().getBackStackEntryCount();
if (backCount == 0)
{
finish();
}
}
});
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.main_container, new OpenGLFragment()).addToBackStack(null).commit();
}
}
}
Activity XML (activity_main.xml):
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
fragment :
public class OpenGLFragment extends Fragment
{
private GLSurfaceView mGLView;
public OpenGLFragment()
{
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
mGLView = new MyGLSurfaceView(this.getActivity()); //I believe you may also use getActivity().getApplicationContext();
return mGLView;
}
}
而且我想您需要按照教程所述制作自己的 GLSurfaceView:
class MyGLSurfaceView extends GLSurfaceView {
public MyGLSurfaceView(Context context){
super(context);
setEGLContextClientVersion(2);
// Set the Renderer for drawing on the GLSurfaceView
setRenderer(new MyRenderer());
}
}
正如教程所说,制作你的渲染器:
public class MyGLRenderer implements GLSurfaceView.Renderer {
public void onSurfaceCreated(GL10 unused, EGLConfig config) {
// Set the background frame color
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}
public void onDrawFrame(GL10 unused) {
// Redraw background color
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
}
public void onSurfaceChanged(GL10 unused, int width, int height) {
GLES20.glViewport(0, 0, width, height);
}
}
关于安卓 OpenGL ES 2 : How to use an OpenGL activity as a fragment in the main activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24886561/