Amos
Amos

Reputation: 1341

Android: calling the same method in different fragments

I have 1 main activity and 4 fragments. Each fragment have the same method name, each does a different thing (initializing data is the same, what each fragment does with the data is different).

At the moment I check which fragment is active and I call that method:

if (getSupportFragmentManager().findFragmentByTag("f1") != null)
   Objects.requireNonNull((FragmentF1) getSupportFragmentManager().findFragmentByTag("f1")).setupData(true);
else if (getSupportFragmentManager().findFragmentByTag("f2") != null)
   Objects.requireNonNull((FragmentF2) getSupportFragmentManager().findFragmentByTag("f2")).setupData(true);

I want to call that method, no matter the fragment I have now. Is it possible?

Also, the requireNonNull is there to avoid the lint warning despite the null check I do one line above, is there a way to make this code cleaner?

Upvotes: 1

Views: 406

Answers (3)

Pavel Poley
Pavel Poley

Reputation: 5577

You can create base class or abstract class for your fragments

public abstract class BaseFragment extends AppCompatActivity {

    abstract void setupData(boolean b);
}

Then each fragments inherit from BaseFragment class and overrides setupData(boolean b). After you find the fragment check if he instace of BaseFragment and call the method

Fragment fragment = getSupportFragmentManager().findFragmentByTag("tag")

    if (fragment instanceof BaseFragment){
         fragment.setupData(true);
       }

Upvotes: 1

huda Olayan
huda Olayan

Reputation: 143

When you should call the method ?

I think in your cause you should use Event bus, so with eventbus when something happen you should post the event to the active fragment

EventBus.getDefault().post("your event here");

and register the event in the fragments so when the fragment is currently launched and the event posted the fragment will receive the event

read more about event bus

Upvotes: 0

Ahmed Bakhet
Ahmed Bakhet

Reputation: 3214

you can declare this method in your activity in which take fragment as parameter and in each time you call this method check on passed fragment and do your logic based on it.

public static void initData(Fragment fragment){
    if (fragment instanceof FirstFragment){
        // Do your logic here
    }else if(fragment instanceof SecondFragment){
        // Do your logic here
    }
}//initData()

Upvotes: 0

Related Questions