Todd DeLand
Todd DeLand

Reputation: 3175

AdView moves above replaced Fragment

Here is a fairly simple layout, basically a Google Map, with an AdView below it. When I replace the entire layout (with FragmentManager), the AdView remains visible and moves to the top of the screen. Why is the AdView still visible? Shouldn't it be replaced just like the MapFragment?

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="@string/banner_ad_unit_id" />
</LinearLayout>

MainActivity.java

getFragmentManager().beginTransaction()
                        .replace(R.id.container, new SettingsFragment())
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                        .addToBackStack(null)
                        .commit();

AdView at bottom

AdView at bottom

AdView at top

AdView at top

Upvotes: 0

Views: 127

Answers (1)

Budius
Budius

Reputation: 39856

This basically happens because the FragmentManager is kind of weird. Point to remember when working with fragments is that:

Fragments created via XML layout should never be replaced.

If you need to replace fragment in the activity you should use all in Java. Something like this:

@Override
public void onCreate(Bundle state){
    super.onCreate(state);
    setContentView(R.layout...);
    if(state == null){
        getFragmentManager()... add initial fragment
    }
}

private void moveToNextFrag(){
     getFragmentManager()
            .beginTransaction()
            .replace(R.id.container, new SettingsFragment())
            .... etc...etc
}

I know it's weird but that's how the FragmentManager operates.

Upvotes: 1

Related Questions