a quick question about managing fragments. Right now I am using this structure:
I have one MainActivity
and multiple Fragments i.e. LoginFragment
, InventoryFragment
, NetworkFragment
etc. I am using the FragmentManager
for transcations and it works greatly so far.
But I have run into one issue. It is about handling the callbacks from the Fragments to the Activity.
I am using the simple way with interface callbacks which I define in the fragments and implement in the MainActivity, but as I get more and more Fragments it is getting really overcrowded with interfaces.
It looks for example like this
public class MainActivity extends AppCompatActivity implements LoginFragmentCallback, InventoryFragmentCallback, NetworkFragmentCallback, AnyFragmentCallback
So my question is how can I manage the communication between Fragment and Activity better?
Thx for any help!
EDIT 1: I got an idea how to solve this with the comment from user @Rohit5k2
In my MainActivity I made a public method
public class MainActivity extends AppCompat{
public callMe();
}
In my Fragment I can call this method via
public class AnyFragment extends Fragment{
private void someMethod(){
((MainActivity)getActivity()).callMe();
}
Seems to solve the problem I think. Or is it bad? With this I dont need to implement any callback since I have a reference to the MainActivity with Fragments.