I have a Three choice to use context in fragment. The first one is using Fragment(context : Context). I think this way is not good because of dependency. The second is using getContext. In java I couldn't use getContext(),but In Kotlin I have known using context(getContext()) is possible(I don't understand why this is possible). And The Third is using GlobalApplicationContext. Which is the best way?
Asked
Active
Viewed 88 times
-1
-
`Fragment(context : Context)` this will crash. `The Third is using GlobalApplicationContext` this is not themed. What's wrong with `.getActivity()`? – EpicPandaForce May 19 '20 at 08:16
-
Check this: https://stackoverflow.com/questions/8215308/using-context-in-a-fragment – Saurabh Thorat May 19 '20 at 08:18
2 Answers
1
Use getActivity(), which returns the activity associated with fragment. The activity is a context (since its extend context) and also using GlobalAppContext is not recommended

HameedR
- 43
- 1
- 6
-
1And in Kotlin you can also use `requireActivitty()` or `requireContext()` to return a non-null version (instead these will throw an exception when the Fragment is not currently attached to an Activity). – RobCo May 19 '20 at 08:21