Matteo Bortolazzo
Matteo Bortolazzo

Reputation: 508

Xamarin Forms - Change tab icon if the tab is active

I need to change the icon of the selected tab in Android with Xamarin Forms 2, like the LinkedIn app.

This is my code but it doens't work:

private void LoadTab(string title, string selectedIcon, string unselectedIcon)
{
    var tab = new ContentPage();
    if (Device.OS == TargetPlatform.iOS) tab.Title = title;
    tab.Icon = new FileImageSource() { File = selectedIcon };
    tab.Appearing += (s, a) => tab.Icon = new FileImageSource() { File = selectedIcon };
    tab.Disappearing += (s, a) => tab.Icon = new FileImageSource() { File = unselectedIcon };
    Children.Add(tab);
}

I've also tried with the PagesChanged event but the result is the same.

This is what the logger writes when I change page:

W/FragmentManager(30781): moveToState: Fragment state for FragmentContainer{e26ef3e #3 id=0x2 android:switcher:2:565409837} not updated inline; expected state 3 found 2

Upvotes: 3

Views: 976

Answers (1)

arsena
arsena

Reputation: 1975

You should create a selector drawable xml instead of just using a png file as an icon. Example:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/selectedIcon" android:state_selected="true"></item>
<item android:drawable="@drawable/selectedIcon" android:state_pressed="true"></item>
<item android:drawable="@drawable/unselectedIcon"></item>

Put it in android project into the drawable folder.

and then: tab.Icon = new FileImageSource() { File = iconSelector };

You don't need to check conditions

Upvotes: 4

Related Questions