以编程方式覆盖视图RelativeLayout

时间:2014-08-29 14:08:53

标签: android android-relativelayout

我想叠加2个观看次数。

我的AdView应该是"浮动"在我的GameView上面。

    RelativeLayout layout = new RelativeLayout(this);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    layout.setLayoutParams(params);

    AdView admobView = createAdView();
    layout.addView(admobView);
    View gameView = createGameView(config);
    layout.addView(gameView);

    setContentView(layout);
    startAdvertising(admobView);


private AdView createAdView() {
    adView = new AdView(this);
    adView.setAdSize(AdSize.SMART_BANNER);
    adView.setAdUnitId(AD_UNIT_ID);
    adView.setId(R.id.classic); // this is an arbitrary id, allows for relative positioning in createGameView()
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
    adView.setLayoutParams(params);
    adView.setBackgroundColor(Color.TRANSPARENT);
    return adView;
}

private View createGameView(AndroidApplicationConfiguration cfg) {
    gameView = initializeForView(new MyGdxGame(), cfg);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
    params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
    params.addRule(RelativeLayout.BELOW, adView.getId());
    gameView.setLayoutParams(params);
    return gameView;
}

这只会将游戏视图设置在广告视图下方。

谢谢

编辑:代码太多......

1 个答案:

答案 0 :(得分:1)

尝试:

private View createGameView(AndroidApplicationConfiguration cfg) {
    gameView = initializeForView(new MyGdxGame(), cfg);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
    params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
    gameView.setLayoutParams(params);
    return gameView;
}

<强>更新

同时更改添加顺序:

View gameView = createGameView(config);
layout.addView(gameView);
AdView admobView = createAdView();
layout.addView(admobView);