3mpetri
3mpetri

Reputation: 599

OpenGL onCreate fragment view in Android

I've created OpenGLRenderer.java class and placed some code in it, shows no errors. Then I placed this code for creating a view in RoomFragment.java fragment:

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);
}}

But I'm getting

The constructor GLSurfaceView(RoomFragment) is undefined

and

The method setContentView(RoomFragment) is undefined for the type RoomFragment

errors. Aren't those methods implemented in header? I'm guessing the reason for that is that this is not an activity, but a fragment which is active only on button click of a previous fragment (which is active on a main activity menu selection).

How do I go about this? How do I create GLSurfaceView in fragments layer?

Upvotes: 3

Views: 3785

Answers (1)

redorav
redorav

Reputation: 962

The GLSurfaceView needs to be related to an Activity by giving it a Context. Fragment does not extend from Activity and from the looks of it, you're trying to create a GLSurfaceView right from inside it.

Also, setContentView must be called from an Activity, essentially what you're saying is 'I want this Activity to be displayed in the way **View is telling it to'. Therefore you have to call the method from the Activity itself.

Try either putting the GLSurfaceView inside the Activity from where you call the Fragment, OR use the Fragment's getActivity() method to retrieve the Activity it's bound to.

The second solution would end up looking like this:

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);
}}

I'm not sure if that's what you're looking for, let me know if it works!

Upvotes: 5

Related Questions