android出现时获取adMob横幅高度

Jau*_*ume 7 java eclipse android admob

我正在向我的应用成功添加adMob横幅广告.当横幅出现时,我需要获得其高度以调整所有布局元素的大小.我正在使用事件onReceivedAd,这是正确触发的.但是,alturaBanner = 0.那么,如何获得它的高度?谢谢.

   /** Called when an ad is received. */
    @Override
    public void onReceiveAd(Ad ad) 
    {
        adView.setVisibility(View.VISIBLE);

        int alturaBanner = adView.getHeight();

        RelativeLayout.LayoutParams params1 = (android.widget.RelativeLayout.LayoutParams) browse2
        .getLayoutParams();

        params1.setMargins(0, alturaBanner, 0, 0);

      Log.d(LOG_TAG, "onReceiveAd");
      Toast.makeText(this, "onReceiveAd", Toast.LENGTH_SHORT).show();
    }
Run Code Online (Sandbox Code Playgroud)

小智 19

在将任何类型的横幅添加到布局之前,您可以获得任何类型横幅的高度.

int heightPixels = AdSize.SMART_BANNER.getHeightInPixels(this);
Run Code Online (Sandbox Code Playgroud)

要么

int heightPixels = AdSize.FULL_BANNER.getHeightInPixels(myContext);
Run Code Online (Sandbox Code Playgroud)

或者用于DIP

int heightDP = AdSize.BANNER.getHeight();
Run Code Online (Sandbox Code Playgroud)

因此,根据您的需要,您可以这样做:

/** Called when an ad is received. */
@Override
public void onReceiveAd(Ad ad) 
{
    adView.setVisibility(View.VISIBLE);

    int alturaBanner = AdSize.BANNER.getHeight(); // This gets the adsize, even if the view is not inflated. 

    RelativeLayout.LayoutParams params1 = (android.widget.RelativeLayout.LayoutParams) browse2
    .getLayoutParams();

    params1.setMargins(0, alturaBanner, 0, 0);

  Log.d(LOG_TAG, "onReceiveAd");
  Toast.makeText(this, "onReceiveAd", Toast.LENGTH_SHORT).show();
}
Run Code Online (Sandbox Code Playgroud)

只需更改AdSize.BANNERAdSize.SMART_BANNER您使用的横幅类型.

添加尺寸获得高度

  • 截至目前,AdSize.SMART_BANNER.getHeight(this); 无效,getHeight()返回无意义的值(在我的情况下为-2). (2认同)

and*_*per 5

在准备之前获取视图的高度将始终返回0.使用下一个代码以获得正确的大小,无论您拥有哪个设备/屏幕:

private static void runJustBeforeBeingDrawn(final View view, final Runnable runnable)
{
    final ViewTreeObserver vto = view.getViewTreeObserver();
    final OnPreDrawListener preDrawListener = new OnPreDrawListener()
    {
        @Override
        public boolean onPreDraw()
        {
            runnable.run();
            final ViewTreeObserver vto = view.getViewTreeObserver();
            vto.removeOnPreDrawListener(this);
            return true;
        }
    };
    vto.addOnPreDrawListener(preDrawListener);
}
Run Code Online (Sandbox Code Playgroud)

在给定的runnable中,您可以查询视图的实际大小.

或者,如果您愿意,可以使用addOnGlobalLayoutListener而不是addOnPreDrawListener.

另一种方法是使用onWindowFocusChanged(并检查hasFocus == true),但这并不总是最好的方法(仅用于创建简单视图,而不用于动态创建)

编辑:runJustBeforeBeingDrawn的替代方案:https://stackoverflow.com/a/28136027/878126