Search code examples
xamarin.formstabstabbedpage

Xamarin forms: Adjacent tab get called when open a tab


I am using TabbedPage for implementing tabs in my apps. I have 4 tabs and always open the second tab initially since the first tab is the home tab. When selecting the second tab third tab is also loading in the background and when selecting the third tab fourth tab is also loading in the background.

TabbedPage Code:

var homePage = new Pages.HomePage()
    {
        Title = "Home"
    };

    var secondPage= new SecondPage()
    {
        Title = "SecondPage"
    };

    var thirdPage = new ThirdPage()
    {
        Title = "ThirdPage"
    };

    var fourthPage = new FourthPage()
    {
        Title = "FourthPage"
    };

    Children.Add(homePage);
    Children.Add(secondPage);
    Children.Add(thirdPage);
    Children.Add(fourthPage);
    CurrentPage = Children[1];

  this.CurrentPageChanged += (object sender, EventArgs e) =>
        {
            var i = this.Children.IndexOf(this.CurrentPage);
            if (i == 0)
            {
                CallHomePage();
            }
            else if (i == 1)
            {
                //SecondPage icon settings
            }
            else if (i == 2)
            {
                //ThirdPage icon settings
            }
            else if (i == 3)
            {
               //FourthPage icon settings
            }
        };

How can I stop the loading of the adjacent tab when selecting a tab?


Solution

  • Solution: You can get the index of currentPage in method OnCurrentPageChanged And if the index equals 1(second page) , use the messagecenter to send message to the page.Refer the following code .

    in Tabbed Page

    protected override void OnCurrentPageChanged()
    {
     base.OnCurrentPageChanged();
    
     int index = Children.IndexOf(CurrentPage);
    
     if (index == 1)
     {
        MessagingCenter.Send<Object>(this, "click_second_tab");
     }
    
     else if (index == 2)
     {
      MessagingCenter.Send<Object>(this, "click_third_tab");
     }
    
     else if (index == 3)
     {
      //...
     }
    } 
    

    in the second page .Move the code that load data from onAppearing to the constructor

    public SecondPage()
    {
    
      //...
      MessagingCenter.Subscribe<Object>(this, "click_second_tab", (obj) =>
      {
         //load your data here
    
      });
    
    }