Android - How to end a Fragment
Asked Answered
S

2

7

In my application I have a navigation drawer, and the way my app works is there is only one activity and if you select something from the Navigation drawer it starts/replaces the current fragment. How Can I make it so that when something is selected from the navigation drawer and a new fragment starts the old fragment ends

I cant do

@Override
public void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    getActivity().finish();
}   

because that would kill the app since there is only one activity.

How do I kill the fragment?

EDIT: my fragment transaction

Home HomeFragment = new Home();
        transaction.replace(R.id.llhome, HomeFragment);
        transaction.addToBackStack(null);
        transaction.commit();
              mDrawerList.setItemChecked(position, true);
                mDrawerLayout.closeDrawer(mDrawerList);

thanks

Stalinsk answered 20/6, 2013 at 20:39 Comment(0)
P
11

Just call:

getActivity().onBackPressed();
Propene answered 22/3, 2014 at 12:23 Comment(0)
D
1

If you are using dynamic fragments, set up via a FragmentTransaction, you could run a transaction to replace() the old fragment with the new one.

Diagnose answered 20/6, 2013 at 20:40 Comment(4)
@user222786: Then I fail to understand your concern. You have successfully replaced the fragment.Diagnose
I have not, the fragment doesnt die, if I went to 5 different fragments, I would have to press back 5 times to get back to the home screen. The fragments arent being killedStalinsk
@Stalinsk Remove transaction.addToBackStack(null);.Haggai
@user222786: I agree with MaciejGórski. If you don't want to add the transaction to the back stack, don't add the transaction to the back stack.Diagnose

© 2022 - 2024 — McMap. All rights reserved.