Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - using same fragment for multiple activities

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.

like image 835
joshua1991 Avatar asked Feb 26 '17 03:02

joshua1991


People also ask

Can I reuse a fragment in multiple activities?

Yes you can, but you have to add more logic to your fragments and add some interfaces for each activity.

Are fragments faster than activities?

Each tab will have a fragment to hold the products. The tabs could either held in activity or a fragment. I do find fragments a slightly faster than activities but really its not something you would really notice in most cases. Regardless if they was intended for speed or not they still seem/feel little quicker.

How do you go from an activity to a fragment in another activity?

1- You can replace or add a new fragment. FragmentTransaction fragmentTransaction = fragmentManager. beginTransaction(); fragmentTransaction . replace( R.


1 Answers

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();
like image 154
Ajay Venugopal Avatar answered Dec 15 '22 22:12

Ajay Venugopal