2012-08-16 86 views

回答

1

我把Admob放在它自己的片段中,只是在整個活動中重複使用這個片段。

+1

任何代碼或教程? – 2012-08-16 11:51:13

4

對於想要演示代碼的人,我在我的應用程序中執行此操作。

使用一個活動+多個片段

  1. 創建MainActivity,本次活動管理所有的片段。在下面的佈局文件中,FrameLayout是片段的容器(用於顯示應用的實際內容),片段是Admob廣告橫幅的容器。

===

<?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> 

===

  • 添加在MainActivity第一片段,這是第一個屏幕,當你開始應用。
  • ==

    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(); 
    

    ==

    的廣告橫幅的佈局

    ==

    <?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> 
    

    ==

    注意:確保在使用此方法時確實要這樣做,例如,在「設置」和「關於」等某些頁面上顯示橫幅的用戶體驗不佳。您可以通過設置AdView到VISIBLE/INVISIBLE/GONE的可見性來輕鬆隱藏/顯示廣告橫幅。