Hello,
Welcome to our Microsoft Q&A platform!
I have also tried setting Badge by creating a custom renderer as suggested in following link ... But it is giving errors and not compiling
What error did you face? I tested a basic demo about the function with the lastest stable packages, it works fine. Here is the related code, you could refer to:
//page.xaml
<ContentPage.ToolbarItems>
<ToolbarItem x:Name="item" Order="Primary" Icon="cart" Text="Item 1" Priority="0" />
</ContentPage.ToolbarItems>
//page.xaml.cs
int badgeValue = 1;
private void Button_Clicked(object sender, EventArgs e)
{
DependencyService.Get<IToolbarItemBadgeService>().SetBadge(this, item, $"{badgeValue}", Color.Red, Color.White);
badgeValue++;
}
The related code on the 'BadgeService' and custom Shell renderer:
//the badge service class
[assembly: Dependency(typeof(ToolbarItemBadgeService))]
namespace ShellToolBarBadgeTest.Droid
{
public class ToolbarItemBadgeService : IToolbarItemBadgeService
{
public void SetBadge(Page page, ToolbarItem item, string value, Color backgroundColor, Color textColor)
{
Device.BeginInvokeOnMainThread(() =>
{
var toolbar = CustomShellToolbarAppearanceTracker.theToolbar;
if (toolbar != null)
{
if (!string.IsNullOrEmpty(value))
{
var index = page.ToolbarItems.IndexOf(item);
if (toolbar.Menu.Size() > index)
{
var menuItem = toolbar.Menu.GetItem(index);
BadgeDrawable.SetBadgeText(MainActivity.Instance, menuItem, value, backgroundColor.ToAndroid(), textColor.ToAndroid());
}
}
}
});
}
}
}
//custom shell renderer
[[assembly: ExportRenderer(typeof(Shell), typeof(CustomShellRenderer))]
namespace ShellToolBarBadgeTest.Droid
{
public class CustomShellRenderer : ShellRenderer
{
public CustomShellRenderer(Context context) : base(context)
{
}
protected override IShellToolbarAppearanceTracker CreateToolbarAppearanceTracker()
{
return new CustomShellToolbarAppearanceTracker(this);
}
}
public class CustomShellToolbarAppearanceTracker : IShellToolbarAppearanceTracker
{
private CustomShellRenderer customShellRenderer;
public static AndroidX.AppCompat.Widget.Toolbar theToolbar;
public CustomShellToolbarAppearanceTracker(CustomShellRenderer customShellRenderer)
{
this.customShellRenderer = customShellRenderer;
}
public void Dispose()
{
}
public void SetAppearance(AndroidX.AppCompat.Widget.Toolbar toolbar, IShellToolbarTracker toolbarTracker, ShellAppearance appearance)
{
theToolbar = toolbar;
}
public void ResetAppearance(AndroidX.AppCompat.Widget.Toolbar toolbar, IShellToolbarTracker toolbarTracker)
{
}
}
}
For the code of the 'BadgeDrawable' class, please check the link you posted.
Best Regards,
Jarvan Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.