hagnr hagnr - 3 months ago 135
C# Question

Change icon on Navigation bar - Xamarin.Forms Android

How can I set different icons in Xamarin.Forms - android.

One for the application, play store, user screen and other for the navigation page.

I updated Project.Droid/MainActivity.cs file:

[Activity(Label = "MyAppName", Icon = "MyIconName", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]


But this way change two icons!!

Other way that I did, I updated ProjectForms/App.cs:

Current.Resources = new ResourceDictionary();
Current.Resources.Add("UlycesColor", Color.FromRgb(121, 248, 81));
var navigationStyle = new Style(typeof(NavigationPage));
var barTextColorSetter = new Setter { Property = NavigationPage.BarTextColorProperty, Value = Color.Black };
var barBackgroundColorSetter = new Setter { Property = NavigationPage.BarBackgroundColorProperty, Value = Color.White };
var barIcon = new Setter { Property = NavigationPage.IconProperty, Value = "newIcon.png" };

navigationStyle.Setters.Add(barTextColorSetter);
navigationStyle.Setters.Add(barBackgroundColorSetter);
navigationStyle.Setters.Add(barIcon);
Current.Resources.Add(navigationStyle);


But doesn't work!!

Any idea???

Answer

You could do it with custom renderer:

[assembly:ExportRenderer (typeof(NavigationPage), typeof(NavigationPageRenderer))]
namespace SuperForms.Samples.Droid
{
    public class NavigationPageRenderer : NavigationRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e)
        {
            base.OnElementChanged(e);

            var actionBar = ((Activity)Context).ActionBar;
            actionBar.SetIcon(Resource.Drawable.newIcon);
        }
    }
}

Add icon to Resources/drawable folder:

enter image description here

How it will looks:

enter image description here