I'm trying to center the adMob to the top CENTER. I'm in landscape mode. I decided to keep using BANNER size instead of SMART_BANNER because of the image support in the first one. It keeps showing in TOP LEFT.
I need to achieve it without xml files, using java code. I'm using 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);
}
use this:
lp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp2.addRule(RelativeLayout.CENTER_HORIZONTAL);
Width of the banner will be same as the activity (screen), height will be as tall as it needs to be.
Remove adsLayout.setGravity(Gravity.TOP);
and use lp2 on the adView, instead of the layout. adsLayout.addView(adView, lp2);
also, you dont need Window
in an Activity, you can use setContentView(adsLayout);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.