android在出现时获取adMob横幅高度

android get adMob banner height when appears(android在出现时获取adMob横幅高度)

本文介绍了android在出现时获取adMob横幅高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

在视图准备好之前获取它的高度总是会返回 0 .无论您拥有哪种设备/屏幕,都可以使用下一个代码来获得正确的尺寸:

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

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

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

或者,如果您愿意,您可以使用 addOnGlobalLayoutListener 代替 addOnPreDrawListener.

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

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

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)

替代 runJustBeforeBeingDrawn:https://stackoverflow.com/a/28136027/878126

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

这篇关于android在出现时获取adMob横幅高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:android在出现时获取adMob横幅高度

基础教程推荐