我正在尝试将adMob集中到顶级中心。我在横向模式。我决定继续使用BANNER尺寸而不是SMART_BANNER,因为第一个支持图像。它一直显示在TOP LEFT。
我需要使用java代码在没有xml文件的情况下实现它。我正在使用RelativeLayout。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandle = new Handler() {
public void handleMessage(Message msg) {
if ((String) msg.obj == "hide") {
adView.setVisibility(View.GONE);
} else {
adView.setVisibility(View.VISIBLE);
}
}
};
RelativeLayout adsLayout;
RelativeLayout.LayoutParams lp2;
Window window;
window = getWindow();
adsLayout = new RelativeLayout(this);
lp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
// Displays Ads at the bottom of your sketch, use Gravity.TOP to display
// them at the top
adsLayout.setGravity(Gravity.TOP); // TOP, BOTTOM
adView = new AdView(this);
adView.setAdUnitId("ca-app-pub-7026369821782045/7333385813");
adView.setAdSize(AdSize.BANNER);
adView.setVisibility(View.GONE);
adsLayout.addView(adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("2BC774A37080BC16DF211A91E61710BA")
.build();
adView.loadAd(adRequest);
window.addContentView(adsLayout, lp2);
}
public void hideAds() {
Message msg = new Message();
msg.obj = "hide";
mHandle.sendMessage(msg);
}
public void showAds() {
Message msg = new Message();
msg.obj = "show";
mHandle.sendMessage(msg);
}
答案 0 :(得分:1)
使用它:
lp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp2.addRule(RelativeLayout.CENTER_HORIZONTAL);
横幅的宽度与活动(屏幕)相同,高度将达到需要的高度。
删除 adsLayout.setGravity(Gravity.TOP);
并在adView上使用lp2,而不是布局。 adsLayout.addView(adView, lp2);
另外,您在活动中不需要Window
,您可以使用setContentView(adsLayout);