android get adMob banner height when appears(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横幅高度
基础教程推荐
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01