Hi,
I implemented a DependencyService to display a dialog with EditText to get user input. Normally I created a AlertDialog.Builder
with new AlertDialog.Builder(Forms.Context);
But after updated Xamarin.Forms it says that the Forms.Context
is deprecated. And I don't think it is a good idea to create a static property for MainActivity
to access its instance. Since I don't know much about how Android manages activity instances.
Here's my code for Android implementation of the service
[assembly: Dependency(typeof(MyApp.Droid.DependencyService.MessagePrompt))]
namespace MyApp.Droid.DependencyService
{
class MessagePrompt : IMessagePrompt
{
async Task<MessagePromptResult> IMessagePrompt.DisplayPromptAsync(string title, string message, string positiveButton, string negativeButton, string placeholder)
{
var completionSource = new TaskCompletionSource<MessagePromptResult>();
var builder = new AlertDialog.Builder(Forms.Context);
if (title != null)
builder.SetTitle(title);
if (message != null)
builder.SetMessage(message);
var input = new EditText(Forms.Context)
{
Left = 10,
Right = 10,
InputType = Android.Text.InputTypes.TextVariationShortMessage,
Hint = placeholder
};
builder.SetView(input);
builder.SetPositiveButton(positiveButton, (s, e) =>
{
completionSource.SetResult(new MessagePromptResult(true, input.Text));
});
builder.SetNegativeButton(negativeButton, (s, e) =>
{
completionSource.SetResult(new MessagePromptResult(false, null));
});
builder.Show();
return await completionSource.Task;
}
}
}