Reputation: 6924
I've added an AdMob banner to the first screen of the app. Now i need it on some other screens (different activities). How do I implement it without reloading banner to avoid extra usage of traffic?
Thanks.
Upvotes: 2
Views: 1914
Reputation: 8727
For someone who want the Demo code, I implement this in my apps.
Use one Activity + multiple Fragments
===
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/adFragment"/>
<fragment
android:id="@+id/adFragment"
android:name="com.jiyuzhai.wangxizhishufazidian.MainActivity$AdFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
===
==
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new MainFragment())
.commit();
}
}
}
==
==
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.addToBackStack("null");
fragmentTransaction.commit();
==
Layout of the Ad banner
==
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="@string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
</RelativeLayout>
==
Note: Be sure you really want to do that when using this approach, for example, that's a not good user experience to show a banner at some page like Settings and About. you can easily hide/show the Ad banner by settings the visibility of the AdView to VISIBLE/INVISIBLE/GONE.
Upvotes: 4
Reputation: 2289
I put Admob in its own fragment and just reuse that fragment across activities.
Upvotes: 1