For those who want demo code, I implement this in my applications.
Use one action + several fragments
- Create MainActivity, this operation manages all fragments. in the layout file below, FrameLayout is the container of your snippets (to display the actual contents of your application), and the snippet is the Admob banner ad container.
===
<?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>
===
- Add the first fragment to MainActivity, this is the first screen when the application starts.
==
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(); } } }
==
- Switch the fragment whenever you want, and the banner will be there (at the bottom of the whole screen) all the time.
==
FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.container, fragment); fragmentTransaction.addToBackStack("null"); fragmentTransaction.commit();
==
Advertising banner layout
==
<?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. Make sure that you really want to do this when using this approach, for example, that a good user interface displays a banner on any page, for example, "Settings" and "About". You can easily hide / show the ad banner by setting the AdView visibility to VISIBLE / INVISIBLE / GONE.
source share