Search code examples
c#androidxamarinxamarin.formsxamarin.android

How to make a method for whenever a user navigates to a page in Xamarin.Android


In my Xamarin.Forms App, I want a method to only be triggered when an Android user goes to a certain page in my application. I know that there is an OnCreate() for the MainActivity.cs, but is there something like this for when a user navigates to a specified page in my Shared Project?

So the method would not be carried out when the app is opened, but when the user of the Android app navigates to a certain page.

Thank you!


Solution

  • all Xamarin Forms pages have an OnAppearing method that will be called when the page displays

    public partial class MyPage : ContentPage
    {
        public MyPage ()
        {
            InitializeComponent ();
        }
    
        public override void OnAppearing()
        {
          // call your method here
        }
    }
    

    you can then use MessagingCenter to send a message from the page to your MainActivity

    in MainActivity

    MessagingCenter.Subscribe<MyPage>(this, "MyPageAppearing", (sender) =>
    {
        // Do something whenever the message is received
    });
    

    and in your page's OnAppearing

    MessagingCenter.Send<MyPage>(this, "MyPageAppearing");