Reputation: 435
I'm developing an Android project with an Activity and some Fragments. The idea is: When the activity is launched it shows the Fragment A, and when the user click on Fragment A button, the activity should replace the Fragment A, whit a new instance of Fragment B, I would like to make the fragments completly independent of the host Activity, as a modular fragments.
So I wanna to implement a simple interface that help me to change the current fragment on the activity to another. In the interface I have create a single method that could manage a FragmentTransaction for any object type inheritance of Fragment class, but I'm little lost with this issue, I have searched and read much documentation but I couldn't get a clear answer about this. I not sure how to do it. I have some code but it's incorrect or incomplete
Here is my interface for my Fragment A:
public interface ActivityInterface {
void replaceFragment(int fragmentId, <? extends Fragment> fragment);
}
this would be the Activity implementation:
public class MyActivity implements ActivityInterface {
public void replaceFragment(int fragmentId, <? extends Fragment> fragment) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(fragmentId, fragment);
fragmentTransaction.commit();
}
}
I am a novice in 'Java Generics' topic so please be clear, I'd appreciate a lot.
Upvotes: 2
Views: 1632
Reputation: 81539
I believe you are looking for this:
public interface ActivityInterface {
<T extends Fragment> void replaceFragment(int fragmentId, T fragment);
}
public class MyActivity implements ActivityInterface {
public <T extends Fragment> void replaceFragment(int fragmentId, T fragment) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(fragmentId, fragment);
fragmentTransaction.commit();
}
}
(although technically I think that'd work just fine with merely void replaceFragment(int fragmentId, Fragment fragment);
)
Upvotes: 1