How to get back from a Fragment to an Activity?

Asked

Viewed 1,162 times

2

I created an Activity of type Drawer Navigation and in the icons of this Activity has an action that takes me to a fragment.

My problem is that I don’t know how to come back from a fragment to an Activity ... how should I get back with the back button from onBackPressed?

I tried to simulate the back button with this but it didn’t work here:

Start fragment:

  public void showMyFragment(View V){
        Fragment fragment = null;
        fragment = new MyFragment();

        if (fragment != null) {
             FragmentManager fragmentManager = getFragmentManager();
             fragmentManager.beginTransaction()
                            .replace(R.id.frame_container, fragment)
                            .addToBackStack(null)
                            .commit();
        }   
}





@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() == 0) {
        this.finish();
    } else {
        getFragmentManager().popBackStack();
    }
}



public class MyFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
            View v=inflater.inflate(R.layout.activity_info, null);
            return v;
        }
    }

2 answers

3


A simple way to do this is to use the addToBackStack(). See how it should be:

FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment)
    .addToBackStack("Fragment").commit();

Thus, you can put a condition by checking whether the entry price of stack has greater value than 0. If yes, use the method popBackStack(), that will return the user to the Fragment previous, otherwise it uses the super.onBackPressed(). Behold:

@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 0 ){
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}

A GIF is worth a thousand images:

inserir a descrição da imagem aqui

This project is saved as navDrawer on Github.

  • 1

    I got it!!! Beautiful! Show!

3

When using addToBackStack(null) is including Fragments in navigation, causing the "Back Button" to display the Fragment previous.

If you don’t want to sail back between the Fragments open do not add to transanction at the backstack. Do not use addToBackStack(null).

Alter

fragmentManager.beginTransaction()
               .replace(R.id.frame_container, fragment)
               .addToBackStack(null)
               .commit();

for

fragmentManager.beginTransaction()
               .replace(R.id.frame_container, fragment)
               .commit();

However, if you want to keep browsing between Fragments and at the same time give the possibility to return to the previous Activity, you have to implement the "Up Button".

Follow the following steps:

  • State what the Activity parent of each Activity is. This is done on Androidmanifist.xml using the attribute android:parentActivityName:

    <application ... >
        ...
    
        <!-- A main/home activity (não tem uma activity pai) -->
    
        <activity
            android:name="com.example.myfirstapp.MainActivity" ...>
            ...
        </activity>
    
        <!-- Uma activity filha da main activity -->
        <activity
            android:name="com.example.myfirstapp.MyChildActivity"
            android:label="@string/title_activity_child"
            android:parentActivityName="com.example.myfirstapp.MainActivity" >
    
            <!-- meta-data para suportar Android 4.0 ou inferior -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.myfirstapp.MainActivity" />
        </activity>
    </application>
    
  • Make "Up Button" available/visible

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }
    
  • Use the static method navigateUpFromSameTask(), de Navutils, to navigate to the parent Activity:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    

For more information see Providing Up Navigation, in the documentation.

Other topics to read:

  • I liked the answer...tomorrow I will implement it friend =D and give you a feedback....

  • Actually do it now. = D

  • Didn’t work out =[

  • What didn’t work? I must have misunderstood your question, because what the answer you accepted suggests is what you already did (use addToBackStack(null)) which forces you to sail back through all the Fragments before returning to Activity.

  • It would be nice if you had a way to navigate programmed. like not coming back from one on one...

  • 1

    I don’t understand. What is proposed in the accepted answer is what you say you don’t want: to go back one by one. We should always follow what is advised by google so that the user experience is always the same, whatever application you are using. In terms of navigation is advised that the "back button" serves to scroll the backstack and the "up button" scroll to higher levels (Activities). That’s what I tried to explain in my reply.

  • Ahhh got it...

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.