以编程方式在底部显示admob广告

时间:2014-09-19 20:02:16

标签: android android-layout admob

我已经阅读了很多关于这个主题的内容,但没有任何作用。我从Android开发者处获取了以下代码:

private AdView adView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    addListenerOnButton();

    // Crear adView.
    adView = new AdView(this);
    adView.setAdUnitId("MY_UNIT_ID");
    adView.setAdSize(AdSize.BANNER);

    // Buscar RelativeLayout suponiendo que se le ha asignado
    // el atributo android:id="@+id/mainLayout".
    RelativeLayout layout = (RelativeLayout)findViewById(R.id.activity_main);

    // Añadirle adView.
    layout.addView(adView);

    // Iniciar una solicitud genérica.
    AdRequest adRequest = new AdRequest.Builder().build();

    // Cargar adView con la solicitud de anuncio.
    adView.loadAd(adRequest);
  } 

@Override
  public void onPause() {
    adView.pause();
    super.onPause();
  }

  @Override
  public void onResume() {
    super.onResume();
    adView.resume();
  }

  @Override
  public void onDestroy() {
    adView.destroy();
    super.onDestroy();
  }

它显示广告,但它不在屏幕的底部。我也尝试过LayoutParams,但一切正常。有任何想法吗?感谢。

1 个答案:

答案 0 :(得分:0)

您可以手动设置坐标,请输入以下代码:

@Override
public void onWindowFocusChanged (boolean hasFocus) {
    //get display height
    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int displayHeight = displaymetrics.heightPixels;

    //get adView height
    int adViewHeight = adView.getHeight();
    int viewStartX = displayHeight = adViewHeight;
    adView.setX(viewStartX);      
}

如果代码不是100%我用手机写的话,你应该得到逻辑