示例#1
0
        // Max of 2 characters
        public static void SetBadgeText(Context context, IMenuItem item, string text, Color backgroundColor, Color textColor)
        {
            if (item.Icon == null)
            {
                return;
            }

            BadgeDrawable badge = null;
            Drawable      icon  = item.Icon;


            if (item.Icon is LayerDrawable)
            {
                LayerDrawable lDrawable = item.Icon as LayerDrawable;

                if (string.IsNullOrEmpty(text) || text == "0")
                {
                    icon = lDrawable.GetDrawable(0);
                    lDrawable.Dispose();
                }
                else
                {
                    for (var i = 0; i < lDrawable.NumberOfLayers; i++)
                    {
                        if (lDrawable.GetDrawable(i) is BadgeDrawable)
                        {
                            badge = lDrawable.GetDrawable(i) as BadgeDrawable;
                            break;
                        }
                    }

                    if (badge == null)
                    {
                        badge = new BadgeDrawable(context, backgroundColor, textColor);
                        icon  = new LayerDrawable(new Drawable[] { item.Icon, badge });
                    }
                }
            }
            else
            {
                badge = new BadgeDrawable(context, backgroundColor, textColor);
                icon  = new LayerDrawable(new Drawable[] { item.Icon, badge });
            }

            badge?.SetBadgeText(text);

            item.SetIcon(icon);
            icon.Dispose();
        }
        public void SetBadge(Page page, ToolbarItem item, string value, Color backgroundColor, Color textColor)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                // var toolbar1 = CrossCurrentActivity.Current.Activity.FindViewById(Resource.Id.toolbar);

                var toolbar = CrossCurrentActivity.Current.Activity.FindViewById(Resource.Id.toolbar) as Android.Support.V7.Widget.Toolbar;
                //  var toolbar = page.ToolbarItems as Android.Support.V7.Widget.Toolbar;

                if (toolbar != null)
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                        var idx = page.ToolbarItems.IndexOf(item);
                        if (toolbar.Menu.Size() > idx)
                        {
                            var menuItem = toolbar.Menu.GetItem(idx);

                            BadgeDrawable.SetBadgeText(CrossCurrentActivity.Current.Activity, menuItem, value, backgroundColor.ToAndroid(), textColor.ToAndroid());
                        }
                    }
                }
            });
        }