简体   繁体   中英

how to show banner ads programmatically

I am trying to implement banner ad but it is messing up with my main layout which is a DrawView. Either mAdview is displayed or DrawView, but not together. I want to show them together.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    size = getIntent().getIntExtra("SIZE", 3);
    setContentView(R.layout.activity_tile);
    drawView = new DrawView(this, size);
    setContentView(drawView);
    setTileSize();

    MobileAds.initialize(this, "ca-app-pub-3940256099942544/6300978111");
    mAdView = findViewById(R.id.adView);
    AdView adView = new AdView(this);
    adView.setAdSize(AdSize.BANNER);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
    adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");

}

XML created

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">

<view class="com.kilnake.patta.picpuzz.TileActivity$DrawView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"/>

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    ads:adSize="BANNER"
    ads:adUnitId="ca-app-pub-3940256099942544/6300978111" />


</LinearLayout>

One problem you face here is how you use setContentView() . This function define which layout to display for this activity. What you do is :

  1. setContentView(R.layout.activity_tile); : you tell to display the layout define in the file activity_tile.xml (what you call your main layout).
  2. setContentView(drawView); : Tell to change what to display, stop display your main layout and display the DrawView
  3. setContentView(layouut); : Cahnge again to stop display the DrawView and display layouut (which contains only the adView)

You need to call this function only once. Define your whole layout in the xml file, by adding the DrawView and the Adview in this file. Then use only setContentView(R.layout.activity_tile);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM