我已经创建了 OpenGLRenderer.java 类并在其中放置了一些代码,没有显示任何错误。然后我在 RoomFragment.java fragment 中放置了用于创建 View 的代码:
public class RoomFragment extends Fragment {
/** Called when the fragment is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GLSurfaceView view = new GLSurfaceView(this);
view.setRenderer(new OpenGLRenderer());
setContentView(this);
}}
但是我得到了
The constructor GLSurfaceView(RoomFragment) is undefined
和
The method setContentView(RoomFragment) is undefined for the type RoomFragment
错误。这些方法不是在标题中实现的吗?我猜这是因为这不是一个 Activity ,而是一个 fragment ,它仅在单击前一个 fragment 的按钮时处于 Activity 状态(在主 Activity 菜单选择中处于 Activity 状态)。
我该怎么做?如何在 fragment 层中创建 GLSurfaceView?
最佳答案
GLSurfaceView 需要通过给它一个 Context
来关联一个 Activity
。 Fragment
不从 Activity
扩展,从它的外观来看,您正在尝试直接从其中创建一个 GLSurfaceView
。
此外,setContentView
必须从 Activity
中调用,基本上您所说的是“我希望此 Activity 以 的方式显示** View
正在告诉它'。因此,您必须从 Activity 本身调用该方法。
尝试将 GLSurfaceView
放在调用 Fragment
的 Activity
中,或者使用 Fragment
的 getActivity()
方法来检索它绑定(bind)到的 Activity
。
第二个解决方案最终看起来像这样:
public class RoomFragment extends Fragment {
/** Called when the fragment is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GLSurfaceView view = new GLSurfaceView(this.getActivity());
view.setRenderer(new OpenGLRenderer());
this.getActivity().setContentView(view);
}}
我不确定这是否是您要找的,如果可行请告诉我!
关于android - Android 中的 OpenGL onCreate fragment View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11667532/