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?
get parent activity by a fragment
1.3k Views Asked by xxddd_69 At
2
There are 2 best solutions below
3

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;
}
You can check an instance of this activity.
getActivity() - can return null value, so you need check this.
Java
Kotlin
Edited: you can also use another method requireActivity the difference is that you receive notNull value, but if activity null you can get IllegalStateException.
requireActivity() - return notNull value but can throw Exception.
Kotlin