How to detect if user requested a tab change on TabbedPage in Xamarin.Forms - xamarin

I have a Xamarin.Forms application which uses a TabbedPage, let's call it T, T consists of 3 ContentPage children A, B and C. Since the usere has the possibility to edit some data on tab B, I want to notify user before leaving tab in order to allow him to cancel the navigation change and save changes first or to discard changes and leave. So far I have managed to override OnBackButtonPressed() method and the navigation bar back button (which would exit TabbedPage). However I quickly noticed that I am still loosing changes when switching between tabs. I would like to override the click on new tab, so I could first present user with the leaving dialog and the skip the change or continue with it. What would be the best way to do this? I am currently working only on Android platform, so solutions on the platform level are also acceptible.
Thank you for your suggestions and feedback :)

I do not think there is an easy way to do this ,
you can use OnDissappearing and OnAppearing for the pages, that is as easy as it gets .
However I think you are using the wrong design.
Having tabs are ment to make it easier to navigate between pages, if you are going to notify the user when changing the tabs then it would be annoying . If I were you i would save the data for each page locally. so when you get back to the page you will have the data anyway.

So in the end I followed the advice of Ahmad and implemented the persisting of data on individual tabs so they are not lost when tabs are switched. (I no longer refresh input fields from data from model when OnAppearing is called).
But in order to know if there are some unsaved changes on my ChildB page, I had to implement the following procedures:
I created the method HandleExit on my ChildB page, which checks for unsaved changes in fields (at least one value in input fields is different from the ones in stored model) and the either prompts the user that there are unsaved changes (if there are some) or pops the navigation stack if there are no changes.
private async Task HandleExit()
{
if(HasUnsavedChanges())
{
var action = await DisplayAlert("Alert", "There are unsaved changes, do you want to discard them?", "Discard changes", "Cancel");
if(!action)
{
return;
}
}
await Navigation.PopAsync();
}
Since there are two ways on how user can return from Tabbed page (pressing the back button on device or pressing the back button in navigation bar, I had to:
A: override the back button method on my ChildB page, so it calls the HandleExit method. But since Navigation.PopAsync() needs to be called on UI thread, I had to explicitly execute the method on UI thread as written below:
protected override bool OnBackButtonPressed()
{
Device.BeginInvokeOnMainThread(new Action(async () =>
{
await HandleExit();
}));
return true;
}
B: Since there is no way to intercept the navigation bar back button on the ContentPage, I had to intercept the event on the platform level (Android) and then pass the event to the ContentPage if necessary via MessagingCenter. So first we need to intercept the event, when navigation bar button is pressed in one of the child pages and send the event via MessagingCenter. We can do that but adding the following method in our MainActivity.cs class:
public override bool OnOptionsItemSelected(IMenuItem item)
{
// check if the current item id
// is equals to the back button id
if (item.ItemId == 16908332)
{
// retrieve the current xamarin forms page instance
var currentpage = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault();
var name = currentpage.GetType().Name;
if(name == "ChildA" || name == "ChildB" || name == "ChildC")
{
MessagingCenter.Send("1", "NavigationBack");
return false;
}
}
return base.OnOptionsItemSelected(item);
}
Now whenever we will press the navigation bar back button in one of the child pages (ChildA, ChildB, ChildC) nothing will happen. But the button will work as before on the rest of the pages. For the second part of solution we need to handle the message from MessagingCenter, so we need to subscribe to it in our ChildB page. We can subsribe to the message topic in OnAppearing method as follows:
MessagingCenter.Subscribe<string>(this, "NavigationBack", async (arg) => {
await HandleExit();
});
Be careful to unsubscribe to the topic in OnDisappearing() otherwise strange things could happen, since there will be references left to your ContentPage even if you pop it from your navigation stack.
Now that we have handled both requests for back navigation in our ChildB page, we also need to handle them in all of remaining child pages (ChildA, ChildC), so they will know if there are unsaved changes in ChildB page, even if it is currently not selected. So the solution is again compraised of handling the device back button, and navigation bar back button, but first we heed a way to check if ChildB has unsaved changes when we are on one of the remaining pages, so we again write HandleExit method but this time it is as follows:
private async Task HandleExit()
{
var root = (TabbedPage)this.Parent;
var editPage = root.Children.Where(x => x.GetType() == typeof(ChildB)).FirstOrDefault();
if(editPage != null)
{
var casted = editPage as ChildB;
if (casted.HasUnsavedChanges())
{
var action = await DisplayAlert("Alert", "There are unsaved changes, do you want to discard them?", "Discard changes", "Cancel");
if (!action)
{
return;
}
}
}
await Navigation.PopAsync();
}
The only thing that remains now is to handle both navigation back events inside remaing child pages. The code for them is the same as in the actual ChildB page.
A: Handling the device back button.
protected override bool OnBackButtonPressed()
{
Device.BeginInvokeOnMainThread(new Action(async () =>
{
await HandleExit();
}));
return true;
}
B: Subscribing to topic from MessagingCenter
MessagingCenter.Subscribe<string>(this, "NavigationBack", async (arg) => {
await HandleExit();
});
If everthing has been done correctly, we should now be prompted with a dialog on any of the child pages if there are unsaved changes on the ChildB page. I hope this will help somebody in the future :)

Related

How to suspend UI / App Shell updates when manually removing and adding element to App Shell in Xamarin.Forms?

My Question:
In Xamarin.Forms 4.2+, can I suspend the App Shell in any way while I am manipulating it? Or can I suspend the whole UI layouting and rending for an instance?
My Situation:
I am creating an App with Xamarin.Forms where I use the new Shell Navigation. Cause I change the Flyout Menu during app runtime, I want to add and remove some of the FlyoutItem by code.
As an example, I have a LoginPage which I want to replace by a UserProfilePage in the App Menu (Flyout Menu). I always have an AppInfoPage in the menu.
Whenever I remove a FlyoutItem, Shell wants to display the next item. So when I remove the LoginPage, Shell displays AppInfoPage or at least calls the constructor and executes the overload of OnAppearing on the AppInfoPage. OnAppearing then does a lot of things to prepare the App info, which is not needed now cause the page will be OnDisappearing just a few ticks later.
Most UI frameworks have some function like this to avoid unneeded UI layouting and rendering. I tried setting IsVisible = false, IsBusy = true and calling BatchBegin(), but none of them helped me.
Code Example:
Check this simplified example, see the TODOs.
private static void SyncAppShell()
{
try {
// TODO Here I want to disable the automatic "navigation on menu modification"
Current.Items.Add(CreateFlyoutItem($"{flyoutIdPrefix}-{nameof(LoginPage)}",
resources[nameof(AppStrings.LoginPage)],
NavigationConstants.LoginPage,
new LoginPage()));
Current.Items.Add(CreateFlyoutItem($"{flyoutIdPrefix}-{nameof(AppInfo)}",
resources[nameof(AppStrings.AppInfo)],
NavigationConstants.AppInfo,
new AppInfo()));
Current.Items.Remove(_staticReferenceToLogoutPage);
}
finally
{
// TODO Here I want to enable the automatic "navigation on menu modification"
}
}
private static FlyoutItem CreateFlyoutItem(string id, string title, string route, ContentPage page, bool isEnabled = true)
{
var flyoutItem = new FlyoutItem { Title = title, StyleId = id, IsEnabled = isEnabled };
flyoutItem.Items.Add(new ShellContent { Route = route, Content = page });
return flyoutItem;
}

Detect Back Arrow Press Of The NavigationPage in Xamarin Forms

Is there any way to detect the press of the back button of the Navigation Page in Xamarin forms?
You can override your navigation page "OnBackButtonPressed" method:
protected override bool OnBackButtonPressed()
{
Device.BeginInvokeOnMainThread(async () =>
{
if (await DisplayAlert("Exit?", "Are you sure you want to exit from this page?", "Yes", "No"))
{
base.OnBackButtonPressed();
await App.Navigation.PopAsync();
}
});
return true;
}
If you are using the shell, you can override the Shell's OnNavigating event:
void OnNavigating(object sender, ShellNavigatingEventArgs e)
{
// Cancel back navigation if data is unsaved
if (e.Source == ShellNavigationSource.Pop && !dataSaved)
{
e.Cancel();
}
}
Update:
OnBackButtonPressed event will get fired ONLY on Android when user press the Hardware back button.
Seems like you are more interested to implement when any page get disappeared you want to do something!
In that case:
You have the page's two methods -
protected override void OnAppearing()
{
base.OnAppearing();
Console.WriteLine("Hey, Im coming to your screen");
}
protected override void OnDisappearing()
{
base.OnDisappearing();
Console.WriteLine("Hey, Im going from your screen");
}
You can override those 2 methods on any page to track when they appear and disappear.
Recent updates to Xamarin forms mean you can now do this in an application made with Shell Navigation for navigation back arrow on both platforms.
Use the Shell.SetBackButtonBehavior method, for example running this code in the constructor of your page object will allow the back navigation to take place only when the bound viewmodel is not busy:
Shell.SetBackButtonBehavior(this, new BackButtonBehavior
{
Command = new Command(async() =>
{
if (ViewModel.IsNotBusy)
{
await Shell.Current.Navigation.PopAsync();
}
})
});
In the body of the Command you can do whatever you need to do when you are intercepting the click of the back button.
Note that this will affect only the navigation back button, not the Android hardware back button - that will need handling separately as per the answers above. You could write a shared method called from both the back button pressed override and the command on shell back button behaviour places to share the logic.
You must override native navigationbar button behavior with custom renderer. OnBackButtonPressed triggers only physical device button. You can read good article how to achive this here

Xamarin forms Navigation issue. Popped page stays active

I have a page "PageA" which listens to a Changed event on a global object.
The page is added in the navigation stack like this:
await Navigation.PushAsync(new PageA());
The page is removed by clicking the back button in the navigation bar.
When I do the same x times, I have x times PageA instances listening to the Changed event. So PageA is created over and over again, but is never really removed.
How do I really get rid of the PageA when clicking the back button?
Example of what you are doing
public partial class MyPage : ContentPage
{
MyPage()
{
this.SomeEvent += SomeEventBeyondTheScopeOfThisPage();
}
protected override void OnDisappearing()
{
//You should add this
this.SomeEvent -= SomeEventBeyondTheScopeOfThisPage();
}
}
Which even if the page is popped from your navigation stack does not remove the reference from MyPage.SomeEvent to SomeEventBeyondTheScopeOfThisPage. So when the Garbage Collector comes along this page is going to stay and this event is going to continue to be listened for.
Just detach the event in OnDisappearing for the simple answer. You dont dispose the page you just detach all references and events outside of its scope. A better idea would be to make your code more modular and not worry about detaching the event. If the event source were coming from within the page itself it would not need to be detached.
public partial class MyPage : ContentPage
{
MyPage()
{
this.SomeEvent += SomeEventWithinPagesScope();
}
private Task SomeEventWithinPagesScope()
{
//My cool event goes here
}
}
If it does have to be global another option would be Messaging Center. I do not believe you have to detach those listeners but I could be wrong.
https://developer.xamarin.com/guides/xamarin-forms/messaging-center/
another reason: NavigationPage.CurrentNavigationTask.Result still refer to the popped page instance. that is why GC will not collect it. unless you navigate to other pages.

Navigation Drawer back button Xamarin

I am using this binding for this awesome Material Drawer Library by MikePenz.
I have implemented the Navigation Drawer with this library and I have also managed to change the hamburger menu to the back arrow when I go level deep. Now I have some problems to get the back arrow to work correctly. When I click on the back arrow, rather than going back to the previous page, it opens up the navigation drawer.
After looking into the original library, I have identified, the following code is responsible to manage the back arrow button. I would appreciate , if someone can help me a bit to write this listener code in C#.
.withOnDrawerNavigationListener(new Drawer.OnDrawerNavigationListener() {
#Override
public boolean onNavigationClickListener(View clickedView) {
//this method is only called if the Arrow icon is shown. The hamburger is automatically managed by the MaterialDrawer
//if the back arrow is shown. close the activity
AdvancedActivity.this.finish();
//return true if we have consumed the event
return true;
}
})
Here is the binding libray that I use : MaterialDrawer-Xamarin
And this is the link to the original Library : MaterialDrawer
Try something like this:
var result = new DrawerBuilder()
.WithActivity(this)
.AddDrawerItems(
//Add some items here
new DividerDrawerItem()
)
.WithOnDrawerNavigationListener(this);
and implement Drawer.IOnDrawerNavigationListener in your activity like this:
public bool OnNavigationClickListener(View clickedView)
{
this.Finish();
return true;
}

Can we override NAVIGATION BACK BUTTON press in Xamarin.forms?

Can we override navigation back button pressed in Xamarin.forms?
I have one navigation back button and the one save button in navigation bar.Save button hits the web service and saves in asynchronous way. While saving although i used progressing bar, navigation back button can be pressed and hence the app crashes due to index out of range exception on navigation stack.I tried using OnDisappearing() , did not work. I wanna cancel the PopUpAsync(),if the save is not done completely, but failed to achieve that. Is there any solution for this scenario? Can we override the navigation back button press event using any custom renderer ?
For controlling the back button to do what I want, I used this method in Xamarin:
public override bool OnKeyDown(Keycode HWkeyCode, KeyEvent e)
{
if (HWkeyCode == Keycode.Back)
{
StartActivity(typeof(FrontPageActivity));
return true;
}
return false;
}

Resources