cronide
cronide

Reputation: 162

Replaced Fragments are still active

I am writing an Android App using the support version of Fragments (android.support.v4.app.Fragment).

I have a strange bug in my code and I dont know how to fix it. When I replace a Fragment with an other one, the replaced one is still active and receiving touch events. A tap on the location of a Button from the replaced Fragment will still fire an OnClick Event.

I really dont know how to fix this. Can anybody help me?

Java Code

Fragment newFragment = new LoginActivityRegisterFragment();

...

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.replace(R.id.login_fragment, newFragment);
ft.commit();

...

XML Layout

...

<fragment
    class="de.myapp.fragments.LoginActivityMainFragment"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/login_fragment" />

...

Upvotes: 1

Views: 1087

Answers (1)

sergej shafarenka
sergej shafarenka

Reputation: 20416

You can replace fragments in a container view only. This means you need a container (not a fragment itself).

<FrameLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/container" />

Then you can initialize it by adding a fragment to it.

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.add(R.id.container, new LoginActivityMainFragment());
ft.commit();

And then you can replace it.

Fragment newFragment = new LoginActivityRegisterFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.replace(R.id.container, newFragment);
ft.commit();

Upvotes: 4

Related Questions