I trying to place an AdMob ad at the top of the screen (above) the Android Actionbar.
A similar question I found is to place an ad at the bottom of a screen with Actionbar showing up. But so far I couldn't figure out how to place it at the top of the screen.
I tried it this way:
private AdView adView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// main view setup
setContentView(R.layout.main);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// actionbar setup
ActionBar actionBar = getActionBar();
actionBar.setTitle("Search");
actionBar.setDisplayHomeAsUpEnabled(true);
final LinearLayout content = (LinearLayout) findViewById(android.R.id.content).getParent();
// Create the adView
adView = new AdView(this, AdSize.BANNER, "ID");
// Lookup your LinearLayout assuming it’s been given
// the attribute android:id="@+id/mainLayout"
// Add the adView to it
FrameLayout.LayoutParams parm = (FrameLayout.LayoutParams) content.getLayoutParams();
parm.gravity = Gravity.TOP;
content.addView(adView);
// Initiate a generic request to load it with an ad
AdRequest adRequest = new AdRequest();
adRequest.addTestDevice("TEST_DEVICE_ID");
adView.loadAd(adRequest);
}
Below you can see a part of the hierarchy viewer of my app. The view "id/main" is my main layout. As you can see on the picture the ActionBar has a id called "id/action_bar_container". In my code above I managed to access the FrameLayout "content" but I wasn't able to access the action_bar_container view. Because they are on the same hierarchy level (I think) it should be possible to access that ActionBar view somehow.
But it didn't work:
Any idea how to achieve that or a link how it could work or an official statement that it doesn't work.
You can usegetRootView()
on any view orgetWindow().getDecorView()
to get thePhoneDecorView
. It has one child - a verticalLinearLayout
.
Add your layout there as the first child.
Note that this is a bad, bad idea. From a user experience point of view, this is a horrific strike against all Design Guidelines. The action bar must be at the top for a multitude of design reasons.
Second, this might break on OEM-themed devices.
Third, what about tablets in landscape, will you really have such a huge bar at the top?
In conclusion, yes, it's possible but it's a horrible idea. Don't do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With