Context Anti-Pattern: Assuming Certain Types

Fragment has a getContext() method that you can call, to retrieve a Context, should you need one for retrieving resources, etc.

It is likely that this Context is the Activity that hosts the fragment. However you should not assume that this Context is the Activity that hosts the fragment. Google has been preparing for cases where fragments might be owned by something else, though what that “something else” is has yet to be determined.

If the documentation for the source of a Context stipulates that it is a particular type of Context, it should be safe to treat it as such, downcasting it as needed (e.g., context as Activity in Kotlin). Otherwise, limit your use of that Context to things that are available on Context and make no assumptions about its concrete type. That concrete type might vary from version to version of Android, or even between devices on the same Android version (due to manufacturer tweaks to Android).


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.