0

I'm developing an android application, I have a problem with the changing of back button function. How i can "replace" the default action of this button ?

I would realize a simple function that allow the user to return to the previous fragment when back button is pressed, for example :

[Main Fragment] ----> [2nd Fragment] [2nd Fragment] <---- [Main Fragment]

I have read some question like this, but i don't understand how to solve my problem.

/**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
        case 0:
            fragment = new HomeFragment(getApplicationContext());
            break;
        case 1:
            fragment = new FindPeopleFragment();
            break;
        case 2:
            fragment = new PhotosFragment();
            break;
        case 3:
            fragment = new CommunityFragment();
            break;
        case 4:
            fragment = new PagesFragment();
            break;
        case 5:
            fragment = new WhatsHotFragment();
            break;

        default:
            break;
        }

This is the part of my code where i call the "new fragment". When i start up my application a new fragment is created (HomeFragment), in this frag i create a new fragment (Fragment_Detail).

What that i want is return from Fragment_Detail to HomeFragment.

I hope I was explanatory

2 Answers2

0

You should take a look at the example: http://developer.android.com/training/implementing-navigation/temporal.html#back-fragments

MillaresRoo
  • 3,808
  • 1
  • 31
  • 37
0

Just add the addToBackStack(null). It will automatically go to the previous fragment loaded in stack.

 HomeFragment  fragment = new HomeFragment();
                FragmentManager manager = getSupportFragmentManager();
                manager.beginTransaction()
                        .replace(R.id.content, fragment,TAG)
                        .commit();

Refer addToBackStack() and refer this answer. Refer the docs

Community
  • 1
  • 1
Akshay Mukadam
  • 2,388
  • 1
  • 27
  • 40
  • R.id.content what is it ? –  Oct 08 '14 at 10:21
  • Its the id of the Layout which where it is going to be placed, second parameter is your Fragment and third parameter is your tag by which you can uniquely itentify it. – Akshay Mukadam Oct 08 '14 at 10:22
  • Refer the basics http://developer.android.com/training/basics/fragments/creating.html and http://developer.android.com/training/basics/fragments/creating.html – Akshay Mukadam Oct 08 '14 at 10:23