Xamarin.Forms 2.5.0 and Context
There are two questions here:
- How do I update Custom Renderers to use a local context?
- How can I access the current context now that
Xamarin.Forms.Forms.Context
is obsolete?
How to Update Custom Renderers
Add the overloaded Constructor to each custom renderer
Here is an example using a ButtonRenderer
[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
namespace MyApp.Droid
{
public class CustomButtonRenderer : ButtonRenderer
{
public CustomButtonRenderer(Context context) : base(context)
{
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
//ToDo: Customize Button
}
}
}
How to Access The Current Context
Install Xamarin.Essentials NugGet Package.
Now, you can call Xamarin.Essentials.Platform.AppContext
when you need to access the current activity.
Here's an example of how to open the App's Settings in Xamarin.Forms.
[assembly: Dependency(typeof(DeepLinks_Android))]
namespace MyApp.Droid
{
public class DeepLinks_Android : IDeepLinks
{
Context CurrentContext => Xamarin.Essentials.Platform.AppContext;
public Task OpenSettings()
{
var myAppSettingsIntent = new Intent(Settings.ActionApplicationDetailsSettings, Android.Net.Uri.Parse("package:" + CurrentContext.PackageName));
myAppSettingsIntent.AddCategory(Intent.CategoryDefault);
return Task.Run(() =>
{
try
{
CurrentContext.StartActivity(myAppSettingsIntent);
}
catch (Exception)
{
Toast.MakeText(CurrentContext.ApplicationContext, "Unable to open Settings", ToastLength.Short);
}
});
}
}
}
I had this same issue for a SearchBarRenderer
and all I needed to do to fix it was add a constructor like so:
public ShowSearchBarRenderer(Context context) : base(context)
{
}
Hope that answers the second part of your question.
use Android.App.Application.Context
There is a discussion of this topic on the Forums