Search code examples
javaandroidlibgdxandroid-view

How to get parent ViewGroup of libgdx game?


I'm trying to add banners ads to my game and for that I need the parent ViewGroup of my libgdx game. My code is:

final Activity activity = (Activity) this;
final ViewGroup parent = (ViewGroup) ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0); // exception here

However the game crashes when I try this with the following error:

java.lang.ClassCastException:
  com.badlogic.gdx.backends.android.surfaceview.GLSurfaceView20
    cannot be cast to android.view.ViewGroup

Solution

  • Try this, initializeForView method return View so get and add to your own layout and at the end setContentView to layout by setContentView method.

    public RelativeLayout layout;
    
    @Override
    protected void onCreate (Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            layout = new RelativeLayout(this);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            layout.setLayoutParams(params);
    
            AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
            View gameView=initializeForView(new Main(), config);
    
            RelativeLayout.LayoutParams gameViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            gameViewParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
            gameViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
            gameView.setLayoutParams(gameViewParams);
    
            layout.addView(gameView);
            //create banner view and embed/add into layout 
    
            setContentView(layout);
    }