Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Fragment back stack causing wired issue

I am having fragment in a single activity in the following sequence.

fragment 1 --> fragment 2 --> fragment 3 --> fragment 4

I am using below code for fragment transaction.

mFragmentTransaction=mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.fragment_container, mFragment,fragmentname);
mFragmentTransaction.addToBackStack(tag);
mFragmentTransaction.commit();

What i want to do is when user is on fragment 3 or 4 then on back press if user is on fragment 4 then fragment 4 --> fragment 3 --> fragment 1. if user is on fragment 3 then fragment 3 --> fragment 1.

I am using following code in onback press.

if(mFragmentManager.findFragmentByTag("fragment 3")!=null){


            mFragmentManager.popBackStack("fragment 2",FragmentManager.POP_BACK_STACK_INCLUSIVE);



        }else{
            super.onBackPressed();
        }

But it cause wired issue on on back press as follow.

fragment 4 --> fragment 1 instead of fragment 4 --> fragment 3 --> fragment 1. fragment 3 --> fragment 1

please help .

like image 203
Bug Avatar asked Feb 13 '26 00:02

Bug


1 Answers

You need to have another nested if statement. You have the one to check if the fragment is null or not, but then you need to check if that fragment is visible.

if(mFragmentManager.findFragmentByTag("fragment 3")!=null){
     if(mFragmentManager.findFragmentByTag("fragment 3").isVisible()){
        mFragmentManager.popBackStack("fragment 2",FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }
}
else{
        super.onBackPressed();
}
like image 110
TronicZomB Avatar answered Feb 14 '26 15:02

TronicZomB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!