7

I want to use a fragment in multiple activities. In the first activity i will use it in, I created it by

    final ScoreBoard fragment = new ScoreBoard();
    getFragmentManager()
            .beginTransaction()
            .add(R.id.fragment_container, fragment)
            .commit();

In the second activity, I have placed the same code in the onCreate() method. However, the fragment keeps resetting and doesn't keep its values in the second activity even though I had saved them through onSavedInstanceState() and onActivityCreated(). Am I recreating the fragment and resetting it? Thank you.

joshua1991
  • 119
  • 2
  • 10
  • See also [How to reuse one Fragment in multiple Activities](https://stackoverflow.com/a/46342916/3681880) – Suragch Sep 21 '17 at 11:38

1 Answers1

4

Yeah you can use same fragment in different activities.

Create a fragment_container view in all activities that you need to call the fragment. Then call the fragment into that container .

ex :

Activity A: calling fragment in Activity A

 final ScoreBoard fragment = new ScoreBoard();
    getFragmentManager()
            .beginTransaction()
            .add(R.id.fragment_container_activityA, fragment)
            .commit();

Activity B: calling fragment in Activity B

 final ScoreBoard fragment = new ScoreBoard();
    getFragmentManager()
            .beginTransaction()
            .add(R.id.fragment_container_activityB, fragment)
            .commit();
Ajay Venugopal
  • 1,544
  • 1
  • 17
  • 30
  • I see. So the fragment container id's has to be different? – joshua1991 Feb 27 '17 at 20:58
  • yeah.. each activity contains different layout and each layout should contain different container . To that container view call the fragment. – Ajay Venugopal Feb 28 '17 at 05:05
  • can we share the SAME INSTANCE of fragment in multiple activities? – mithil1501 Nov 14 '18 at 07:41
  • @mithil1501 Could you please explain the scenario you need to do with a fragment. – Ajay Venugopal Nov 14 '18 at 12:51
  • @AjayVenugopal What if I have let's say Activity1 which has a fragment instance named Fragment1. I want the exact same instance of Fragment1 to show in Activity2 too so that if the user changes a view state say a ToggleButton when interacting with Acticity2 (which has the fragment instance) and closes Activity2, by going back to Activity1, the change will be appear on Acticity1 (which has the same Fragment1 instance). – Hichem Acher Jul 02 '20 at 19:57