簡體   English   中英

如何獲取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的后代, SurfaceViewView的后代, 而不是 ViewGroup

如何獲取libgdx游戲的父ViewGroup?

回答您的問題:父級可能是ViewGroup也可能不是ViewGroup (在您的情況下不是)。 您可以獲取內容View並執行instanceof test來查看它是否是ViewGroup的后代

嘗試此操作, initializeForView方法返回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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM