Amine Messabhia
Amine Messabhia

Reputation: 542

Two Fragments, two different layouts, one activity

i have one activity, which runs fragment A at start in a RelativeLayout,

after that, inside this fragment, i try to open another fragment B, which is somehow an overlay only, it runs in another RelativeLayout, to look above fragment A, so far, all is working good, but the problem is in the onBackPressed():

I open the overlay fragment B, then i press back button, but it closes fragment A only.

Here is my activity's xml

<RelativeLayout
    android:id="@+id/main_fragment_replacement"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</RelativeLayout>

<RelativeLayout
    android:background="#0000"
    android:id="@+id/overlay_fragment_replacement"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

I think this should explain it, but i'm up to provide any additional info.

Upvotes: 1

Views: 69

Answers (3)

EvOlaNdLuPiZ
EvOlaNdLuPiZ

Reputation: 600

In the android documentation for Fragments it mentions this process.

If you don't call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and is later resumed if the user navigates back.

Upvotes: 0

kon
kon

Reputation: 66

When adding Fragments, you can add them to your backstack.

getSupportManager()
        .beginTransaction()
        .replace(R.id.container, fragment)
        .addToBackStack(null)
        .commit();

Then you can simply check how many fragment are in your backstack and remove e.g. Fragment B when 2 when the backstack contains two fragments.

Upvotes: 1

Petros Mosoyan
Petros Mosoyan

Reputation: 258

You can use tags. Before opening fragment B, set the tag equal to for example "a". Override the onBackPressed() method and check the value of the tag. If it equal to "a" then open the fragment a. If it equal to "b" then open fragment b.

Upvotes: 1

Related Questions