Where does code for defining alert builder go? MainPage.cs or MainActivity.cs?

Viewed 66

Guys am trying to build an alert dialog to show up when a button is fired on the main page in Xamarin but am confused because imports for using android os utilities have been included in the MainActivity.cs, when i insert the alert dialog code in the MainActivity.cs and point the event handler from the event caller in the MainPage.xaml(button), The compiler reports that the event handler was not found in the MainPage.cs when i cut the code from MainActivity to MainPage.cs i get errors due to Android Namspace that haven't been used please help...Here is the code

  private void Showmessage(Object sender , EventArgs e)
        {
            var dialog = new AlertDialog.Builder(this);
            {
                dialog.SetTitle("Alert Title");
                dialog.SetMessage("Your wifi has a working internet connection");
                dialog.Show();
            }
        }

In the MainActivity.cs, it shows no errors because all the android imports have been included but when i put in the MainPage.cs it reports errors because the Android Namespace haven't been used... Here are the imports in the MainPage.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;


using Xamarin.Forms;

1 Answers

AlertDialog.Builder is an api of Native Xamarin.Android.

In MainActivity, you can use Native Xamarin.Android apis,so your code will work.

In MainPage.cs, you should use Xamarin.forms apis which can be used for both iOS and Android platform, to display a alert, you can use:

  private async void Showmessage(Object sender , EventArgs e)
        {
            await DisplayAlert ("Alert", "You have been alerted", "OK");
        }

Here is the document Display Pop-ups;

Related