Felix
Felix

Reputation: 56

Change Paddin from TabbedPage's NavigationBar

Im building an app and I want to change the padding of the navigationbar of my TabbedPage. I'm writing it in Xamarin (C#). I want the navigationbar to have a distance of e.g 20pixels to all sides of the display. How do I achieve that? (image shows what I mean)enter image description here

Upvotes: 1

Views: 248

Answers (1)

Lia
Lia

Reputation: 523

From the image you provided, I believe what you're asking is to add Margin instead of padding to the Tab bar. And here is how we can achieve it by leveraging Custom Renderer:

[assembly: ExportRenderer(typeof(CustomTabbedPage), typeof(CustomTabbedPageRenderer))]
namespace TabbedPageDemo.Droid
{
    class CustomTabbedPageRenderer: TabbedPageRenderer
    {
        public CustomTabbedPageRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
        {
            base.OnElementChanged(e);
            TabLayout tabLayout = (TabLayout)ViewGroup.GetChildAt(1);
            int tabCount = tabLayout.TabCount;
            for (int i = 0; i < tabCount; i++)
            {
                Android.Views.View tab = ((ViewGroup)tabLayout.GetChildAt(0)).GetChildAt(i);
                ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams)tab.LayoutParameters;
                if (i == 0)
                {
                    p.SetMargins(50, 50, 0, 0); // set left + top margin for the first tabbar item
                }
                else if (i == tabCount - 1)
                {
                    p.SetMargins(0, 50, 50, 0); // set top + right margin for the last tabbar item
                }
                else {
                    p.SetMargins(0, 50, 0, 0); // set top margin for the rest tabbar item
                }
                tab.RequestLayout();
                tab.SetBackgroundColor(Android.Graphics.Color.LightGray);//add background color to highlight the tabbar area
            }
        }
    }
}

Use the CustomTabbedPage in your xaml and you'll get something like the screenshot: enter image description here

Upvotes: 2

Related Questions