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

设置将视图以编程方式对齐到屏幕底部时出现问题。 基本上我只想把我的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()); 

谁能帮我吗?

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

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

 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); 
 RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); p.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId()); 

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

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

而不仅仅是

 rl.addView(adView); 

祝你好运! 🙂

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