Sunday, September 9, 2018

Use the activity context for UI-related operations

Many Android API calls require a Context. Activity objects serve as contexts, but a different context can be acquired with getApplicationContext(). One might be inclined to call that function from inside an inner class when a Context is necessary, but when doing anything UI-related, using the enclosing activity class's this is a much better idea. Using the application context is likely to use a different theme than the activity, which can make the elements of inflated layouts look weird. In my application, that made text views use the wrong color and become extremely difficult to read on some (but not all!) devices.

No comments:

Post a Comment