android - using same fragment for multiple activities
A

1

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.

Auberge answered 26/2, 2017 at 3:0 Comment(1)
See also How to reuse one Fragment in multiple ActivitiesTelluride
W
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();
Wifeless answered 27/2, 2017 at 12:13 Comment(5)
I see. So the fragment container id's has to be different?Auberge
yeah.. each activity contains different layout and each layout should contain different container . To that container view call the fragment.Wifeless
can we share the SAME INSTANCE of fragment in multiple activities?Plata
@Plata Could you please explain the scenario you need to do with a fragment.Wifeless
@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).Parasol

© 2022 - 2024 — McMap. All rights reserved.