Android View在没有XML的情况下对齐底部(以编程方式)

时间:2011-07-03 13:28:45

标签: android xml alignment

我遇到了设置将视图以编程方式对齐到屏幕底部的问题。基本上我只想把我的admob广告放在屏幕底部。我不能用XML来做,因为它会更麻烦。现在我已经让广告正常工作,并将其手动添加到RelativeLayout,但默认情况下它显示在屏幕顶部。我尝试使用重力命令,但无法使其正常工作。

以下是代码段:

    _glSurfaceView = new CCGLSurfaceView(this);

    adView = new AdView(this, AdSize.BANNER, "a14e04559caea39");
    adView.loadAd(new AdRequest());
    adView.setGravity(Gravity.BOTTOM);

    RelativeLayout rl = new RelativeLayout(this);

    rl.addView(_glSurfaceView);
    rl.addView(adView);     

    setContentView(rl);
    adView.loadAd(new AdRequest());

任何人都可以帮助我吗?

4 个答案:

答案 0 :(得分:30)

蜻蜓的回答对我有用。 以下是参考资料的完整代码段

adView = new AdView(this, AdSize.BANNER, "xxxxxxxxxxxxxxx");
panel = new MySurfaceView(this);

AdRequest adRequest = new AdRequest();
adRequest.addTestDevice(AdRequest.TEST_EMULATOR);

RelativeLayout rl = new RelativeLayout(this);
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.WRAP_CONTENT, 
    RelativeLayout.LayoutParams.WRAP_CONTENT);

lay.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

rl.addView(panel);
rl.addView(adView, lay);

setContentView(rl);

adView.loadAd(adRequest);

答案 1 :(得分:10)

RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
 p.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId());

答案 2 :(得分:8)

使用LayoutParams将广告添加到RelativeLayout,如下所示:

RelativeLayout.LayoutParams rparams = (LayoutParams) rl
            .getLayoutParams();
    rparams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    ((ViewGroup) rl).addView(adView, rparams);

而不仅仅是

rl.addView(adView);   
祝你好运! :)

答案 3 :(得分:0)

    ImageButton buttonAdvance = new ImageButton(this);
    RelativeLayout.LayoutParams params = new       RelativeLayout.LayoutParams(160, 160);
    params.leftMargin = 5;
    params.bottomMargin = 4;
    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    buttonAdvance.setLayoutParams(params);