Home > Enterprise >  Why does OnAppearing not fire every time in Android
Why does OnAppearing not fire every time in Android

Time:06-05

I have a Xamarin project. When I run in UWP OnAppearing initially fires once and then loads the Login Page. After successfully logging in, my Main page fires OnAppearing again and I load data into my ViewModel.

However, if I run the project in Android, OnAppearing only fires once - When the Main page initially loads.

protected override async void OnAppearing()
{
    if (!App.IsUserLoggedIn)
    {
        await App.NavigationService.NavigateModalAsync(PageNames.LoginPage, false);
    }
    else
    {
        ((SchedulerViewModel)Schedule.BindingContext).LoadData();
    }

    base.OnAppearing();
}

Why does Android only fire once? Or is UWP the one misbehaving?

CodePudding user response:

NOTE: NavigationService is not a standard Xamarin Forms class. I assume it is built on top of Page.Navigation.PushModalAsync and PopModalAsync.


This is documented behavior of Modal Stack on Android:

Popping Pages from the Modal Stack:

When PopModalAsync is invoked, the following events occur: ... The page being returned to has its OnAppearing override invoked, provided that the underlying platform isn't Android.

NOTE: it seems to depend on the API version of Android. I just tested it on API 30, and Android did fire OnAppearing again, when modal page was popped.


Instead of code in OnAppearing, I would solve it like this:

In App.xaml.cs, instead of:

MainPage = new MainPage();

do:

if (!App.IsUserLoggedIn)
    MainPage = new LoginPage();
else
    MainPage = new MainPage();

Then when LoginPage is done, instead of pop modal, do:

Application.Current.MainPage = new MainPage();

NOTE: Adapt as needed, if these are pages inside NavigationPage or AppShell.

  • Related