Set (or highlight) a specific shell tabbar item after navigation

64 Views Asked by At

I've added notifications to my android app. When a system level notification in recieved and clicked, the app opens the NotificationView to display the related message retrieved from the server.

Using the following code within MainActivity.cs during the OnNewIntent setup, the app navigates back to the AllNotificationsView (which is a tab in the shell) when the user presses the back button from the detail view. Fantastic.

 Shell.Current.GoToAsync($"/{nameof(AllNotificationsPage)}/{nameof(NotificationPage)}", true,
     new Dictionary<string, object>
     {
         ["Notification"] = notification
     }
 );

In this scenario, when both of these views are open, I'd like the Shell's Notification tab to be highlighted.

I thought this docs page would help me out, but the app doesn't seem to pick up the name set for the tab in question.

Shell.Current.CurrentItem = allNotifications;

Any help or pointers in the right direction would be appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

The code in the post get's me 2/3 of the way there.

Update your AppSell.xaml to use some names for the tabbar and the item you want to switch to.

<TabBar x:Name="shellTabBar">
        <ShellContent
            x:Name="details"
            // other code />

        <ShellContent
            x:Name="allNotifications"
            //other code />
</TabBar>

We can then add a method to AppShell.xaml.cs to switch the currently selected tab.

public void SwitchtoTab()
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            shellTabBar.CurrentItem = allNotifications;
        });
    }

Which can then be called from the MainActivity.cs file (or anywhere else), just before triggering the navigation.

((AppShell)App.Current.MainPage).SwitchtoTab();

All credit to this answer.