我正在尝试在我的游戏中添加横幅广告,为此我需要我的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
答案 0 :(得分:0)
您的根布局为<metadata>
<groupId>com.typesafe.play</groupId>
<artifactId>filters-helpers_2.12</artifactId>
<versioning>
<latest>2.6.0-M2</latest>
<release>2.6.0-M2</release>
<versions>
<version>2.6.0-M1</version>
<version>2.6.0-M2</version>
</versions>
<lastUpdated>20170310220437</lastUpdated>
</versioning>
</metadata>
,它是GLSurfaceView20
的后代,后者是SurfaceView
的后代,不是 a View
。< / p>
如何获取libgdx游戏的父ViewGroup?
回答你的问题:父母可能是也可能不是ViewGroup
(在你的情况下不是)。您可以获取内容ViewGroup
并执行View
测试,看看它是否是instanceof
答案 1 :(得分:0)
试试这个,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);
}