Is it possible to use common fragment generate function globally?

624 views Asked by At

I have common fragment generate function like the following:

// Common Fragment generation method
public void generateFragment(String speechString, String buttonString) {

    // Store data to be passed to the fragment in bundle format
    Bundle args = new Bundle();
    args.putString("Speech", speechString);
    args.putString("ButtonTitle", buttonString);

    // Instantiate Speech fragment and set arguments
    SpeechFragment newFragment = new SpeechFragment();
    newFragment.setArguments(args);

    // Dynamically add fragment to view using fragment transaction
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.commit();
}

I made this function to use multiple times in one of my activity. Now, I found that this function can be used with my another activity.
I also have global variable class but it extends Application. Yes I know global variable or global function should be declared in a class which extends Application class.
So I can't put the function contains getSupportFragmentManager() which connected with activity as global one.

Does anyone know such a function to use between activity?

Thank you!

1

There are 1 answers

2
FunkTheMonk On BEST ANSWER

You could just pass the fragment manager into the method:

public static void generateFragment(FragmentManager fragmentManager, String speechString, String buttonString)

I would avoid having a BaseActivity as others have suggested, because it limits you to what you can extend from: e.g. FragmentActivity, ActionBarActivity, ListActivity, PreferenceActivity, e.t.c. Google "composition over inheritance" to see why this is a bad approach.

Really, what you probably want to do is to split this method up.

In SpeechFragment.java:

public static SpeechFragment newInstance(String speechString, String buttonString) {
    // Store data to be passed to the fragment in bundle format
    Bundle args = new Bundle();
    args.putString("Speech", speechString);
    args.putString("ButtonTitle", buttonString);

    // Instantiate Speech fragment and set arguments
    SpeechFragment newFragment = new SpeechFragment();
    newFragment.setArguments(args);
    return newFragment;
}

The SpeechFragment class will then be responsible on how to initiate itself. The rest of the method

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, SpeechFragment.newInstance(speechString, buttonString);
transaction.commit();

Can then just be part of the classes where this Fragment is used. You then have the flexibility of changing the container id, which FragmentManager to use (could use the child FragmentManager of a Fragment instead), adding / attaching e.t.c instead of replacing - depending on how that fragment needs to be used in the activity.