アプリの最初の画面に AdMob バナーを追加しました。今、私は他のいくつかの画面(異なるアクティビティ)でそれを必要としています。トラフィックの余分な使用を避けるために、バナーをリロードせずに実装するにはどうすればよいですか?
ありがとう。
アプリの最初の画面に AdMob バナーを追加しました。今、私は他のいくつかの画面(異なるアクティビティ)でそれを必要としています。トラフィックの余分な使用を避けるために、バナーをリロードせずに実装するにはどうすればよいですか?
ありがとう。
デモ コードが必要な人のために、これをアプリに実装します。
1 つのアクティビティ + 複数のフラグメントを使用する
===
<?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();
==
広告バナーのレイアウト
==
<?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 に設定することで、Ad バナーを簡単に非表示/表示できます。
Admob を独自のフラグメントに入れ、そのフラグメントをアクティビティ間で再利用するだけです。