I'm currently having two activities, MainActivity and ResultActivity and both of them will use the same fragment - Favorite. my question is: How to know which activity is containing the fragment? For example I have a fragment A inside activity ResultActivity, and how can I know if fragment A is contained in ResultActivity or MainActivity?
CodePudding user response:
You can check an instance of this activity.
Java
if (getActivity() instanceof MainActivity) {
// TODO
} else if (getActivity() instanceof ResultActivity) {
// TODO
}
Kotlin
if (activity is MainActivity) {
// TODO
} else if (activity is ResultActivity) {
// TODO
}
CodePudding user response:
I think this is the best practice for you.
And to get Activity you should use requireActivity()
And to get Context you should use requireContext()
// for kotlin
fun isMainActivity(): Boolean {
return requireActivity() is MainActivity
}
public boolean isMainActivity() {
return requireActivity() instanceof MainActivity;
}