Pages

Wednesday, 29 November 2017

Xamarin.Forms 2.5 and Local Context in Android Custom Renderers

If you’ve updated any of your solutions to use Xamarin.Forms 2.5, you may have noticed compiler warnings that say “Context is obsolete as of version 2.5. Please use a local context instead”. This warning typically occurs on Android custom renderers, and any references to Xamarin.Forms.Forms.Context.

The warning occurs on Android custom renderers because the parameterless constructors have been marked obsolete. This change was made to support native embedding in Android apps that use multiple activities. Instead, the custom renderer base classes now have constructors that take a Android.Content.Context argument. In addition, Xamarin.Forms.Forms.Context has been marked obsolete because it was a global static reference to an Activity, which is not ideal.

Custom renderer implementations in applications can be fixed by adding a constructor that takes a Android.Content.Context argument and passing it to the base class constructor, as shown in the following code example:

Technically the constructor isn’t required (unless you’re using native embedding in an Android app that has multiple activities) – the backwards compatibility built into Xamarin.Forms will take care of it. However, adding the constructor will eliminate the compiler warning, and produce some peace of mind.

If your custom renderer accesses Xamarin.Forms.Forms.Context, you should most likely just be using the view’s context, which is passed into the custom renderer constructor.