monogon
monogon

Reputation: 21

How can I place an AdView above a preference fragment?

I have a settings activity which holds a preference fragment. I want to place an adView (banner ad) above this fragment.

So far I managed to show the ad banner but the banner is displayed behind the fragment (my fragment has transparent background so I see the ad but it is covered by the text of preference fragment).

How can I place the ad banner in front of the fragment? Any help is highly appreciated! Thank you.

This is my code in the settings activity:

public class Settings extends Activity  {

public static PrefsFragment mPrefsFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);       

    setContentView(R.layout.settings_layout);

    if (savedInstanceState == null) {
        mPrefsFragment = new PrefsFragment();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(android.R.id.content, mPrefsFragment).commit();
    }

}

@Override
public void onResume() {

    super.onResume();

    AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().addTestDevice("1234").build();
    mAdView.loadAd(adRequest);

}

[......]

}

And my 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="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>

Upvotes: 0

Views: 907

Answers (1)

mears
mears

Reputation: 501

In the fragment that welcomes the preferences, you can do something like this.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    LinearLayout v = (LinearLayout) super.onCreateView(inflater, container, savedInstanceState);
    AdView adView = new AdView(getContext());
    adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
    adView.setAdSize(AdSize.BANNER);


    AdRequest request1 = new AdRequest.Builder().build();
    adView.loadAd(request1);
    v.addView(adView);
    return v;
}

Upvotes: 3

Related Questions