android get adMob banner height when appears

admob, android, eclipse, java

Solution

getting the height of the view before it was prepared will always return you 0 . use the next code in order to get its correct size , no matter which device/screen you have:

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

inside the given runnable , you can query the real size of the view.

alternatively , you can use addOnGlobalLayoutListener instead of addOnPreDrawListener if you wish.

another approach is to use onWindowFocusChanged (and check that hasFocus==true) , but that's not always the best way ( only use for simple views-creation, not for dynamic creations)

EDIT: Alternative to runJustBeforeBeingDrawn: https://stackoverflow.com/a/28136027/878126

Problem

I am adding an adMob banner to my app successfully. When banner appears I need to get its height in order to resize all layout elements. I am using the event onReceivedAd, that is properly fired. However, alturaBanner is = 0. Then, how to get its height? thank you. ``` /** 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(); } ```

Original source

Related problems