Search code examples
androidandroid-fragmentsfragmenttransaction

How to navigate from fragment in one activity to fragment in another activity?


I want to add back navigation to toolbar. I need to get from a fragment in an activity to a specific fragment in another activity.

It looks a little like this, where every orange line means navigating to a new activity or fragment:

enter image description here

How do I move from fragment B to fragment A from OtherActivity?


Solution

  • Consider these steps:

    From Activity 1 holding Fragment A , you want to directly load Fragment B in Activity 2.

    Now, I am thinking first, then you press a button in Fragment A, you can directly go to Activity B.

    Then it means, you can simply load Fragment B as soon as you arrive in Activity 2.

    Since you are dealing with back navigation (I believe you mean the upNavigation?), you can override the following:

    But watch clearly, because if you need to load an exact fragment in Activity 2, you need to know somehow:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
    
            case android.R.id.home:
                Intent intent = new Intent(this, Activity2.class);
                intent.putExtra("frag", "fragmentB");
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    
    }
    

    As you can see, when you click the back arrow on the toolbar, we pass a value through our intent to identity which fragment we want to load.

    Next, in your Activity2, simply get the intent extra and do a switch or an if statement:

    @Override
    public void onResume(){
      super.onResume();
    
      Intent intent = getIntent();
    
      String frag = intent.getExtras().getString("frag");
    
      switch(frag){
    
        case "fragmentB":
           //here you can set Fragment B to your activity as usual;
            fragmentManager.beginTransaction().replace(R.id.container_body, new FragmentB()).commit();
           break;
      }
    }
    

    From here, you should have your Fragment B showing in Activity 2.

    Now you can handle the same thing while inside Activity 2 to decide where to go when a user clicks the back home arrow!

    I hope this helps you get an idea.

    Note: I thought about the interface approach and realized it is not necessary since this can be done easily with this approach!