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:
[assembly: ExportRenderer(typeof(MyEntry), typeof(MyEntryRenderer))] namespace CustomRenderer.Android { class MyEntryRenderer : EntryRenderer { public MyEntryRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (Control != null) { Control.SetBackgroundColor(global::Android.Graphics.Color.LightGreen); } } } }
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.
Thanks David... Solved the warning in a WebViewRenderer...
ReplyDeleteHow should you approach replacing Forms.Context in an Android class accessed through the dependency resolver? Here is an example
ReplyDeletepublic class VersionHelper : IVersionHelper
{
public string GetVersionNumber()
{
var versionNumber = string.Empty;
Context context = Forms.Context;
if (context != null)
{
versionNumber = context.PackageManager.GetPackageInfo(context.PackageName, 0).VersionName;
}
return versionNumber;
}
}
I'll do a blog post on this today.
ReplyDeleteThanks David. I was expecting a few lines in reply. A whole blog post is spectacular!
ReplyDelete