Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show previous fragment

How to remove current and show previous fragment? Like if I'm press "Back" button

I'm using such construction:

FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.remove(fragment).commit();

But it just removes current fragment, without showing previous

like image 281
Dmitry Zaytsev Avatar asked Feb 01 '12 18:02

Dmitry Zaytsev


People also ask

How do I go back to a previous fragment from activity?

2 Answers. Show activity on this post. and when you click on back button in the toolbar programmatically go back to the previous fragment using following code.

How to replace fragments in android?

Use replace() to replace an existing fragment in a container with an instance of a new fragment class that you provide. Calling replace() is equivalent to calling remove() with a fragment in a container and adding a new fragment to that same container.

What is fragment transaction?

A Fragment represents a behavior or a portion of user interface in an Activity . You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.


2 Answers

You have to call FragmentTransaction.addToBackStack(null) where you add the fragment and then call FragmentManager.popBackStack() when you want to remove it.

like image 122
Gian U. Avatar answered Sep 20 '22 17:09

Gian U.


Add this method in your activity:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if( this.getFragmentManager().getBackStackEntryCount() != 0 ){
                this.getFragmentManager().popBackStack();
                return true;
            }
            // If there are no fragments on stack perform the original back button event
        }

        return super.onKeyDown(keyCode, event);
    }

Then where you are changing the fragments do this:

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, new YourFragmentName());
transaction.addToBackStack(null); // this is needed for the above code to work
transaction.commit();
like image 25
Adil Malik Avatar answered Sep 21 '22 17:09

Adil Malik