Friso
Friso

Reputation: 2428

How do I get rid of overlapping fragments?

I'm working on an app where I want to be able to go to a new detail fragment from another detail fragment, but when I click on the back button I want to always return to the master fragment, no matter how many times I attached a new detail fragment.

With the below code I got that effect, but when I hit back the last detail fragment is displayed as an overlay on the master fragment and when I try to attach a new detail fragment it is displayed on top of the master fragment instead of replacing it.

How can I fix this?

if (getSupportFragmentManager().findFragmentByTag(TAG_MASTER).isVisible()) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container, fragment, TAG_DETAIL);
            transaction.addToBackStack(TAG_MASTER);
            transaction.commit();
        } else {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container, fragment, TAG_DETAIL);
            transaction.commit();
        }

Upvotes: 0

Views: 58

Answers (1)

eclipse1203
eclipse1203

Reputation: 635

Override onBackPressed in your activity. Keep in mind this is semi-psuedo code

@Override
public void onBackPressed() {
    if ("Not on your master fragment") {
        // replace R.id.container with your master fragment
    } else {
        super.onBackPressed();
    }
}

Upvotes: 1

Related Questions