Search code examples
android.netmauimvvm-toolkit

.Net Maui Fill Top-Tabbar Horizontal


Is it possible to fill the horizontal space with only two tabbar-items on Mobile? At the moment the items are aligned on the left, I would like to have them stretched over the whole possible space.

TopBar Image

Image

Shell xaml:

<FlyoutItem FlyoutDisplayOptions="AsMultipleItems">
    <Tab Title="NFC-Toolkit" >
        <ShellContent 
            Title="Read" 
            Route="Read"
            ContentTemplate="{DataTemplate view:ReadPage}"/>
        <ShellContent 
            Title="Taglists" 
            Route="TagLists"
            ContentTemplate="{DataTemplate view:TagListPage}"/>       
    </Tab>
    
</FlyoutItem>

I have already searched for some time in the documentation and found nothing about it.

I want it to be like this: Topbar expectation

image


Solution

  • This is achievable by using a custom handler so that you can stretch over the whole horizontal space with even width.

    You can refer to the detailed steps below:

    1.Create a custom ShellRenderer class:CustomShellHandler under Platform/Android:

    public class CustomShellHandler : ShellRenderer
    {
          public CustomShellHandler(Context context) : base(context)
          {
          }
    
          protected override IShellTabLayoutAppearanceTracker CreateTabLayoutAppearanceTracker(ShellSection shellSection)
          {
               return new MyTabLayoutAppearanceTracker(this);
          }
    }
    
    public class MyTabLayoutAppearanceTracker : ShellTabLayoutAppearanceTracker
    {
           public MyTabLayoutAppearanceTracker(IShellContext shellContext) : base(shellContext)
           {
           }
           public override void SetAppearance(TabLayout tabLayout, ShellAppearance appearance)
            {
                base.SetAppearance(tabLayout, appearance);
                // the key is to set the TabMode and TabGravity
                tabLayout.TabMode = TabLayout.ModeFixed;
                tabLayout.TabGravity = TabLayout.GravityFill;
            }
    }
    
    
    1. In MauiProgram.cs, register the CustomShellHandler as below:
         .ConfigureMauiHandlers(handlers => {
    #if ANDROID
    
           handlers.AddHandler(typeof(Shell), typeof(CustomShellHandler));
    #endif
    });
    
    

    Output:

    enter image description here