如何获取 libgdx 游戏的父 ViewGroup?

How to get parent ViewGroup of libgdx game?

我正在尝试将横幅广告添加到我的游戏中,为此我需要 libgdx 游戏的父 ViewGroup。我的代码是:

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

然而,当我尝试此操作时游戏崩溃并出现以下错误:

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

您的根布局是 GLSurfaceView20,它是 SurfaceView 的后代,它是 View 的后代,不是 a ViewGroup.

How to get parent ViewGroup of libgdx game?

回答您的问题:parent 可能是也可能不是 ViewGroup(在您的情况下不是)。可以获取内容View,进行instanceof测试,看是否是ViewGroup

的后代

试试这个 initializeForView 方法 return View 获取并添加到您自己的布局,最后通过 setContentView 方法将 setContentView 设置为布局。

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