How to get back from a fragment to an activity?

2

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

My problem is that I do not know how to go back from a fragment to an activity ... how should I do to go back with the back button of onBackPressed?

I tried to simulate the back button with this but it did not 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;
        }
    }
    
asked by anonymous 17.02.2017 / 21:19

2 answers

3

One simple way to do this is to use the addToBackStack() . Here's how it should look:

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

So you can put a condition checking that the stack input dimension has a value greater than 0 . If yes, use the popBackStack() method, which will return the user to the previous fragment , otherwise it uses super.onBackPressed() . See:

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

A GIF is worth more than a thousand images:

Thisprojectissavedas navDrawer in GitHub.

    
17.02.2017 / 23:16
3

Using addToBackStack(null) is including the fragments in the navigation, causing the "Back Button" to display the previous fragment .

If you do not want to navigate backwards between the fragments open do not add transanction to backstack . Do not use addToBackStack(null) .

Change

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 navigating fragments and at the same time giving the possibility to return to the previous Activity, you must implement the "Up Button".

Follow the steps below:

  • Declare which is the parent Activity of each Activity. This is done in AndroidManifist.xml using the android:parentActivityName attribute:

    <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 the "Button Up" available / visible

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }
    
  • Use the static method navigateUpFromSameTask() , from 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:

18.02.2017 / 13:00