コード例 #1
0
        public static bool UseGradients(this GradientDrawable gradientDrawable)
        {
            if (!NativeVersion.IsAtLeast(24))
            {
                return(false);
            }

            var colors = gradientDrawable.GetColors();

            return(colors != null && colors.Length > 1);
        }
コード例 #2
0
    private async Task PrepareAndPlayMediaPlayerAsync()
    {
        try
        {
            if (NativeVersion.IsAtLeast(21))
            {
                MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();

                await mediaPlayer.SetDataSourceAsync(ApplicationContext, AndroidNet.Uri.Parse(AudioUrl));

                await metaRetriever.SetDataSourceAsync(AudioUrl, new Dictionary <string, string>());

                var focusResult = audioManager.RequestAudioFocus(new AudioFocusRequestClass
                                                                 .Builder(AudioFocus.Gain)
                                                                 .SetOnAudioFocusChangeListener(this)
                                                                 .Build());

                if (focusResult != AudioFocusRequest.Granted)
                {
                    // Could not get audio focus
                    Console.WriteLine("Could not get audio focus");
                }

                UpdatePlaybackState(PlaybackStateCode.Buffering);
                mediaPlayer.PrepareAsync();

                AquireWifiLock();
                UpdateMediaMetadataCompat(metaRetriever);
                StartNotification();

                byte[] imageByteArray = metaRetriever.GetEmbeddedPicture();
                if (imageByteArray == null)
                {
                    Cover = await BitmapFactory.DecodeResourceAsync(Resources, Resource.Drawable.player_play);
                }
                else
                {
                    Cover = await BitmapFactory.DecodeByteArrayAsync(imageByteArray, 0, imageByteArray.Length);
                }
            }
        }
        catch (Exception ex)
        {
            UpdatePlaybackState(PlaybackStateCode.Stopped);

            mediaPlayer.Reset();
            mediaPlayer.Release();
            mediaPlayer = null;

            // Unable to start playback log error
            Console.WriteLine(ex);
        }
    }
コード例 #3
0
ファイル: ShellPageContainer.cs プロジェクト: hevey/maui
        public ShellPageContainer(Context context, IVisualElementRenderer child, bool inFragment = false) : base(context, child, inFragment)
        {
            if (child.Element.Handler is INativeViewHandler nvh &&
                nvh.VirtualView.Background == null)
            {
                var color = NativeVersion.IsAtLeast(23) ?
                            Context.Resources.GetColor(AColorRes.BackgroundLight, Context.Theme) :
                            new AColor(ContextCompat.GetColor(Context, AColorRes.BackgroundLight));

                nvh.NativeView.SetBackgroundColor(color);
            }
        }
コード例 #4
0
        protected SemanticHeadingLevel GetSemanticHeading(IViewHandler viewHandler)
        {
            // AccessibilityHeading is only available on API 28+
            // With lower Apis you use ViewCompat.SetAccessibilityHeading
            // but there exists no ViewCompat.GetAccessibilityHeading
            if (NativeVersion.IsAtLeast(28))
            {
                return(((View)viewHandler.NativeView).AccessibilityHeading
                                        ? SemanticHeadingLevel.Level1 : SemanticHeadingLevel.None);
            }

            return(viewHandler.VirtualView.Semantics.HeadingLevel);
        }
コード例 #5
0
        void RestoreFocusability(AView nativeView)
        {
            nativeView.ImportantForAccessibility = ImportantForAccessibility.Auto;

            if (NativeVersion.IsAtLeast(26))
            {
                nativeView.SetFocusable(ViewFocusability.FocusableAuto);
            }

            if (nativeView is ViewGroup vg)
            {
                vg.DescendantFocusability = DescendantFocusability.BeforeDescendants;
            }
        }
コード例 #6
0
        void RemoveFocusability(AView nativeView)
        {
            nativeView.ImportantForAccessibility = ImportantForAccessibility.NoHideDescendants;

            if (NativeVersion.IsAtLeast(26))
            {
                nativeView.SetFocusable(ViewFocusability.NotFocusable);
            }

            // Without setting this the keyboard will still navigate to components behind the modal page
            if (nativeView is ViewGroup vg)
            {
                vg.DescendantFocusability = DescendantFocusability.BlockDescendants;
            }
        }
コード例 #7
0
        public static void MapBarBackground(NavigationPageHandler handler, NavigationPage view)
        {
            var NavPage            = handler.VirtualViewWithValidation();
            var barBackgroundBrush = NavPage.BarBackground;

            if (Brush.IsNullOrEmpty(barBackgroundBrush) &&
                NavPage.BarBackgroundColor != null)
            {
                barBackgroundBrush = new SolidColorBrush(NavPage.BarBackgroundColor);
            }

            if (barBackgroundBrush == null)
            {
                return;
            }

            var navController = handler._controlsNavigationController;
            var NavigationBar = navController.NavigationBar;

            if (NativeVersion.IsAtLeast(13))
            {
                var navigationBarAppearance = NavigationBar.StandardAppearance;

                navigationBarAppearance.ConfigureWithOpaqueBackground();

                //if (barBackgroundColor == null)
                //{
                //	navigationBarAppearance.BackgroundColor = ColorExtensions.BackgroundColor;

                //	var parentingViewController = GetParentingViewController();
                //	parentingViewController?.SetupDefaultNavigationBarAppearance();
                //}
                //else
                //	navigationBarAppearance.BackgroundColor = barBackgroundColor.ToUIColor();

                var backgroundImage = NavigationBar.GetBackgroundImage(barBackgroundBrush);
                navigationBarAppearance.BackgroundImage = backgroundImage;

                NavigationBar.CompactAppearance    = navigationBarAppearance;
                NavigationBar.StandardAppearance   = navigationBarAppearance;
                NavigationBar.ScrollEdgeAppearance = navigationBarAppearance;
            }
            else
            {
                var backgroundImage = NavigationBar.GetBackgroundImage(barBackgroundBrush);
                NavigationBar.SetBackgroundImage(backgroundImage, UIBarMetrics.Default);
            }
        }
コード例 #8
0
        public override bool ShouldInvalidateLayoutForBoundsChange(CGRect newBounds)
        {
            if (newBounds.Size == _currentSize)
            {
                return(base.ShouldInvalidateLayoutForBoundsChange(newBounds));
            }

            if (NativeVersion.IsAtLeast(11))
            {
                UpdateConstraints(CollectionView.AdjustedContentInset.InsetRect(newBounds).Size);
            }
            else
            {
                UpdateConstraints(CollectionView.Bounds.Size);
            }

            return(true);
        }
コード例 #9
0
        protected override MauiSearchBar CreateNativeView()
        {
            var searchBar = new MauiSearchBar()
            {
                ShowsCancelButton = true, BarStyle = UIBarStyle.Default
            };

            if (NativeVersion.IsAtLeast(13))
            {
                _editor = searchBar.SearchTextField;
            }
            else
            {
                _editor = searchBar.FindDescendantView <UITextField>();
            }

            return(searchBar);
        }
コード例 #10
0
        public override UICollectionViewLayoutInvalidationContext GetInvalidationContext(UICollectionViewLayoutAttributes preferredAttributes, UICollectionViewLayoutAttributes originalAttributes)
        {
            if (preferredAttributes.RepresentedElementKind != UICollectionElementKindSectionKey.Header &&
                preferredAttributes.RepresentedElementKind != UICollectionElementKindSectionKey.Footer)
            {
                if (NativeVersion.IsAtLeast(12))
                {
                    return(base.GetInvalidationContext(preferredAttributes, originalAttributes));
                }

                try
                {
                    // We only have to do this on older iOS versions; sometimes when removing a cell that's right at the edge
                    // of the viewport we'll run into a race condition where the invalidation context will have the removed
                    // indexpath. And then things crash. So

                    var defaultContext = base.GetInvalidationContext(preferredAttributes, originalAttributes);
                    return(defaultContext);
                }
                catch (MonoTouchException ex) when(ex.Name == "NSRangeException")
                {
                    Application.Current?.FindMauiContext()?.CreateLogger <ItemsViewLayout>()?.LogWarning(ex, "NSRangeException");
                }

                UICollectionViewFlowLayoutInvalidationContext context = new UICollectionViewFlowLayoutInvalidationContext();
                return(context);
            }

            // Ensure that if this invalidation was triggered by header/footer changes, the header/footer are being invalidated

            UICollectionViewFlowLayoutInvalidationContext invalidationContext = new UICollectionViewFlowLayoutInvalidationContext();
            var indexPath = preferredAttributes.IndexPath;

            if (preferredAttributes.RepresentedElementKind == UICollectionElementKindSectionKey.Header)
            {
                invalidationContext.InvalidateSupplementaryElements(UICollectionElementKindSectionKey.Header, new[] { indexPath });
            }
            else if (preferredAttributes.RepresentedElementKind == UICollectionElementKindSectionKey.Footer)
            {
                invalidationContext.InvalidateSupplementaryElements(UICollectionElementKindSectionKey.Footer, new[] { indexPath });
            }

            return(invalidationContext);
        }
コード例 #11
0
        internal ModalWrapper(INativeViewHandler modal)
        {
            _modal = modal;

            var elementConfiguration = modal.VirtualView as IElementConfiguration <Page>;

            if (elementConfiguration?.On <PlatformConfiguration.iOS>()?.ModalPresentationStyle() is PlatformConfiguration.iOSSpecific.UIModalPresentationStyle style)
            {
                var result = style.ToNativeModalPresentationStyle();

                if (!NativeVersion.IsAtLeast(13) && result == UIKit.UIModalPresentationStyle.Automatic)
                {
                    result = UIKit.UIModalPresentationStyle.FullScreen;
                }

                if (result == UIKit.UIModalPresentationStyle.FullScreen)
                {
                    Color modalBkgndColor = ((Page)_modal.VirtualView).BackgroundColor;

                    if (modalBkgndColor?.Alpha > 0)
                    {
                        result = UIKit.UIModalPresentationStyle.OverFullScreen;
                    }
                }

                ModalPresentationStyle = result;
            }

            UpdateBackgroundColor();
            View.AddSubview(modal.ViewController.View);
            TransitioningDelegate = modal.ViewController.TransitioningDelegate;
            AddChildViewController(modal.ViewController);

            modal.ViewController.DidMoveToParentViewController(this);

            if (NativeVersion.IsAtLeast(13))
            {
                PresentationController.Delegate = this;
            }

            ((Page)modal.VirtualView).PropertyChanged += OnModalPagePropertyChanged;
        }
コード例 #12
0
        protected override MauiDatePicker CreateNativeView()
        {
            MauiDatePicker nativeDatePicker = new MauiDatePicker();

            _picker = new UIDatePicker {
                Mode = UIDatePickerMode.Date, TimeZone = new NSTimeZone("UTC")
            };

            if (NativeVersion.IsAtLeast(14))
            {
                _picker.PreferredDatePickerStyle = UIDatePickerStyle.Wheels;
            }

            var width   = UIScreen.MainScreen.Bounds.Width;
            var toolbar = new UIToolbar(new RectangleF(0, 0, width, 44))
            {
                BarStyle = UIBarStyle.Default, Translucent = true
            };
            var spacer     = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace);
            var doneButton = new UIBarButtonItem(UIBarButtonSystemItem.Done, (o, a) =>
            {
                SetVirtualViewDate();
                nativeDatePicker.ResignFirstResponder();
            });

            toolbar.SetItems(new[] { spacer, doneButton }, false);

            nativeDatePicker.InputView          = _picker;
            nativeDatePicker.InputAccessoryView = toolbar;

            nativeDatePicker.InputView.AutoresizingMask          = UIViewAutoresizing.FlexibleHeight;
            nativeDatePicker.InputAccessoryView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight;

            nativeDatePicker.InputAssistantItem.LeadingBarButtonGroups  = null;
            nativeDatePicker.InputAssistantItem.TrailingBarButtonGroups = null;

            nativeDatePicker.AccessibilityTraits = UIAccessibilityTrait.Button;

            return(nativeDatePicker);
        }
コード例 #13
0
        protected ItemsViewLayout(ItemsLayout itemsLayout, ItemSizingStrategy itemSizingStrategy = ItemSizingStrategy.MeasureFirstItem)
        {
            ItemSizingStrategy = itemSizingStrategy;

            _itemsLayout = itemsLayout;
            _itemsLayout.PropertyChanged += LayoutOnPropertyChanged;

            var scrollDirection = itemsLayout.Orientation == ItemsLayoutOrientation.Horizontal
                                ? UICollectionViewScrollDirection.Horizontal
                                : UICollectionViewScrollDirection.Vertical;

            Initialize(scrollDirection);

            if (NativeVersion.IsAtLeast(11))
            {
                // `ContentInset` is actually the default value, but I'm leaving this here as a note to
                // future maintainers; it's likely that someone will want a Platform Specific to change this behavior
                // (Setting it to `SafeArea` lets you do the thing where the header/footer of your UICollectionView
                // fills the screen width in landscape while your items are automatically shifted to avoid the notch)
                SectionInsetReference = UICollectionViewFlowLayoutSectionInsetReference.ContentInset;
            }
        }
コード例 #14
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            ItemsSource = CreateItemsViewSource();

            if (!NativeVersion.IsAtLeast(11))
            {
                AutomaticallyAdjustsScrollViewInsets = false;
            }
            else
            {
                // We set this property to keep iOS from trying to be helpful about insetting all the
                // CollectionView content when we're in landscape mode (to avoid the notch)
                // The SetUseSafeArea Platform Specific is already taking care of this for us
                // That said, at some point it's possible folks will want a PS for controlling this behavior
                CollectionView.ContentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehavior.Never;
            }

            RegisterViewTypes();

            EnsureLayoutInitialized();
        }
コード例 #15
0
        internal CGSize GetReferenceSizeForheaderOrFooter(UICollectionView collectionView, DataTemplate template, NSString elementKind, nint section)
        {
            if (!_isGrouped || template == null)
            {
                return(CGSize.Empty);
            }

            if (ItemsSource.GroupCount < 1 || section > ItemsSource.GroupCount - 1)
            {
                return(CGSize.Empty);
            }

            if (!NativeVersion.IsAtLeast(11))
            {
                // iOS 10 crashes if we try to dequeue a cell for measurement
                // so we'll use an alternate method
                return(MeasureSupplementaryView(elementKind, section));
            }

            var cell = GetViewForSupplementaryElement(collectionView, elementKind,
                                                      NSIndexPath.FromItemSection(0, section)) as ItemsViewCell;

            return(cell.Measure());
        }
コード例 #16
0
 public static FontWeight GetFontWeight(this Typeface typeface) =>
 NativeVersion.IsAtLeast(28)
                         ? (FontWeight)typeface.Weight
                         : typeface.IsBold ? FontWeight.Bold : FontWeight.Regular;
コード例 #17
0
        public static void MapBarTextColor(NavigationPageHandler handler, NavigationPage view)
        {
            var NavPage = handler.VirtualViewWithValidation();

            var navController = handler._controlsNavigationController;
            var NavigationBar = navController.NavigationBar;

            var barTextColor = NavPage.BarTextColor;

            if (NavigationBar == null)
            {
                return;
            }

            // Determine new title text attributes via global static data
            var globalTitleTextAttributes = UINavigationBar.Appearance.TitleTextAttributes;
            var titleTextAttributes       = new UIStringAttributes
            {
                ForegroundColor = barTextColor == null ? globalTitleTextAttributes?.ForegroundColor : barTextColor.ToNative(),
                Font            = globalTitleTextAttributes?.Font
            };

            // Determine new large title text attributes via global static data
            var largeTitleTextAttributes = titleTextAttributes;

            if (NativeVersion.IsAtLeast(11))
            {
                var globalLargeTitleTextAttributes = UINavigationBar.Appearance.LargeTitleTextAttributes;

                largeTitleTextAttributes = new UIStringAttributes
                {
                    ForegroundColor = barTextColor == null ? globalLargeTitleTextAttributes?.ForegroundColor : barTextColor.ToNative(),
                    Font            = globalLargeTitleTextAttributes?.Font
                };
            }

            if (NativeVersion.IsAtLeast(13))
            {
                if (NavigationBar.CompactAppearance != null)
                {
                    NavigationBar.CompactAppearance.TitleTextAttributes      = titleTextAttributes;
                    NavigationBar.CompactAppearance.LargeTitleTextAttributes = largeTitleTextAttributes;
                }

                NavigationBar.StandardAppearance.TitleTextAttributes      = titleTextAttributes;
                NavigationBar.StandardAppearance.LargeTitleTextAttributes = largeTitleTextAttributes;

                if (NavigationBar.ScrollEdgeAppearance != null)
                {
                    NavigationBar.ScrollEdgeAppearance.TitleTextAttributes      = titleTextAttributes;
                    NavigationBar.ScrollEdgeAppearance.LargeTitleTextAttributes = largeTitleTextAttributes;
                }
            }
            else
            {
                NavigationBar.TitleTextAttributes = titleTextAttributes;

                if (NativeVersion.IsAtLeast(11))
                {
                    NavigationBar.LargeTitleTextAttributes = largeTitleTextAttributes;
                }
            }

            //// set Tint color (i. e. Back Button arrow and Text)
            //var iconColor = Current != null ? NavigationPage.GetIconColor(Current) : null;
            //if (iconColor == null)
            //	iconColor = barTextColor;

            //NavigationBar.TintColor = iconColor == null || NavPage.OnThisPlatform().GetStatusBarTextColorMode() == StatusBarTextColorMode.DoNotAdjust
            //	? UINavigationBar.Appearance.TintColor
            //	: iconColor.ToUIColor();
        }
コード例 #18
0
        public void OnLongPress(MotionEvent e)
        {
            if (!HasAnyDragGestures())
            {
                return;
            }

            SendEventArgs <DragGestureRecognizer>(rec =>
            {
                if (!rec.CanDrag)
                {
                    return;
                }

                var element = GetView();
                // TODO MAUI FIX FOR COMPAT
                //var renderer = AppCompat.Platform.GetRenderer(element);
                var v = (AView)element.Handler.NativeView;

                if (v.Handle == IntPtr.Zero)
                {
                    return;
                }

                var args = rec.SendDragStarting(element);

                if (args.Cancel)
                {
                    return;
                }

                CustomLocalStateData customLocalStateData = new CustomLocalStateData();
                customLocalStateData.DataPackage          = args.Data;


                // TODO MAUI
                string clipDescription  = String.Empty;               //AutomationPropertiesProvider.ConcatenateNameAndHelpText(element) ?? String.Empty;
                ClipData.Item item      = null;
                List <string> mimeTypes = new List <string>();

                if (!args.Handled)
                {
                    if (args.Data.Image != null)
                    {
                        mimeTypes.Add("image/jpeg");
                        item = ConvertToClipDataItem(args.Data.Image, mimeTypes);
                    }
                    else
                    {
                        string text = clipDescription ?? args.Data.Text;
                        if (Uri.TryCreate(text, UriKind.Absolute, out _))
                        {
                            item = new ClipData.Item(AUri.Parse(text));
                            mimeTypes.Add(ClipDescription.MimetypeTextUrilist);
                        }
                        else
                        {
                            item = new ClipData.Item(text);
                            mimeTypes.Add(ClipDescription.MimetypeTextPlain);
                        }
                    }
                }

                var dataPackage        = args.Data;
                ClipData.Item userItem = null;
                if (dataPackage.Image != null)
                {
                    userItem = ConvertToClipDataItem(dataPackage.Image, mimeTypes);
                }

                if (dataPackage.Text != null)
                {
                    userItem = new ClipData.Item(dataPackage.Text);
                }

                if (item == null)
                {
                    item     = userItem;
                    userItem = null;
                }

                ClipData data = new ClipData(clipDescription, mimeTypes.ToArray(), item);

                if (userItem != null)
                {
                    data.AddItem(userItem);
                }

                var dragShadowBuilder = new AView.DragShadowBuilder(v);

                customLocalStateData.SourceNativeView = v;
                customLocalStateData.SourceElement    = element;

                if (NativeVersion.IsAtLeast(24))
                {
                    v.StartDragAndDrop(data, dragShadowBuilder, customLocalStateData, (int)ADragFlags.Global | (int)ADragFlags.GlobalUriRead);
                }
                else
#pragma warning disable CS0618 // Type or member is obsolete
                {
                    v.StartDrag(data, dragShadowBuilder, customLocalStateData, (int)ADragFlags.Global | (int)ADragFlags.GlobalUriRead);
                }
#pragma warning restore CS0618 // Type or member is obsolete
            });
        }
コード例 #19
0
        void LoadRecognizers()
        {
            if (ElementGestureRecognizers == null)
            {
                return;
            }

#if __MOBILE__
            if (_shouldReceiveTouch == null)
            {
                // Cache this so we don't create a new UITouchEventArgs instance for every recognizer
                _shouldReceiveTouch = ShouldReceiveTouch;
            }

            UIDragInteraction?uIDragInteraction = null;
            UIDropInteraction?uIDropInteraction = null;

            if (_dragAndDropDelegate != null && _nativeView != null)
            {
                foreach (var interaction in _nativeView.Interactions)
                {
                    if (interaction is UIDragInteraction uIDrag && uIDrag.Delegate == _dragAndDropDelegate)
                    {
                        uIDragInteraction = uIDrag;
                    }

                    if (interaction is UIDropInteraction uiDrop && uiDrop.Delegate == _dragAndDropDelegate)
                    {
                        uIDropInteraction = uiDrop;
                    }
                }
            }

            bool dragFound = false;
            bool dropFound = false;
#endif
            if (_nativeView != null &&
                _handler.VirtualView is View v &&
                v.TapGestureRecognizerNeedsDelegate() &&
                (_nativeView.AccessibilityTraits & UIAccessibilityTrait.Button) != UIAccessibilityTrait.Button)
            {
                _nativeView.AccessibilityTraits |= UIAccessibilityTrait.Button;
                _addedFlags |= UIAccessibilityTrait.Button;
                _defaultAccessibilityRespondsToUserInteraction     = _nativeView.AccessibilityRespondsToUserInteraction;
                _nativeView.AccessibilityRespondsToUserInteraction = true;
            }

            for (int i = 0; i < ElementGestureRecognizers.Count; i++)
            {
                IGestureRecognizer recognizer = ElementGestureRecognizers[i];

                if (_gestureRecognizers.ContainsKey(recognizer))
                {
                    continue;
                }

                var nativeRecognizer = GetNativeRecognizer(recognizer);
                if (nativeRecognizer != null && _nativeView != null)
                {
#if __MOBILE__
                    nativeRecognizer.ShouldReceiveTouch = _shouldReceiveTouch;
#endif
                    _nativeView.AddGestureRecognizer(nativeRecognizer);

                    _gestureRecognizers[recognizer] = nativeRecognizer;
                }

#if __MOBILE__
                if (NativeVersion.IsAtLeast(11) && recognizer is DragGestureRecognizer)
                {
                    dragFound            = true;
                    _dragAndDropDelegate = _dragAndDropDelegate ?? new DragAndDropDelegate(_handler);
                    if (uIDragInteraction == null && _handler.NativeView != null)
                    {
                        var interaction = new UIDragInteraction(_dragAndDropDelegate);
                        interaction.Enabled = true;
                        _handler.NativeView.AddInteraction(interaction);
                    }
                }

                if (NativeVersion.IsAtLeast(11) && recognizer is DropGestureRecognizer)
                {
                    dropFound            = true;
                    _dragAndDropDelegate = _dragAndDropDelegate ?? new DragAndDropDelegate(_handler);
                    if (uIDropInteraction == null && _handler.NativeView != null)
                    {
                        var interaction = new UIDropInteraction(_dragAndDropDelegate);
                        _handler.NativeView.AddInteraction(interaction);
                    }
                }
#endif
            }

#if __MOBILE__
            if (!dragFound && uIDragInteraction != null && _handler.NativeView != null)
            {
                _handler.NativeView.RemoveInteraction(uIDragInteraction);
            }

            if (!dropFound && uIDropInteraction != null && _handler.NativeView != null)
            {
                _handler.NativeView.RemoveInteraction(uIDropInteraction);
            }
#endif

            var toRemove = new List <IGestureRecognizer>();

            foreach (var key in _gestureRecognizers.Keys)
            {
                if (!ElementGestureRecognizers.Contains(key))
                {
                    toRemove.Add(key);
                }
            }

            for (int i = 0; i < toRemove.Count; i++)
            {
                IGestureRecognizer gestureRecognizer = toRemove[i];
                var uiRecognizer = _gestureRecognizers[gestureRecognizer];
                _gestureRecognizers.Remove(gestureRecognizer);

                if (_nativeView != null)
                {
                    _nativeView.RemoveGestureRecognizer(uiRecognizer);
                }

                uiRecognizer.Dispose();
            }
        }
コード例 #20
0
        static void UpdateMenuItem(AToolbar toolbar,
                                   ToolbarItem item,
                                   int?menuItemIndex,
                                   IMauiContext mauiContext,
                                   Color tintColor,
                                   PropertyChangedEventHandler toolbarItemChanged,
                                   List <IMenuItem> previousMenuItems,
                                   List <ToolbarItem> previousToolBarItems,
                                   Action <Context, IMenuItem, ToolbarItem> updateMenuItemIcon = null)
        {
            var   context = mauiContext.Context;
            IMenu menu    = toolbar.Menu;

            item.PropertyChanged -= toolbarItemChanged;
            item.PropertyChanged += toolbarItemChanged;

            IMenuItem menuitem;

            Java.Lang.ICharSequence newTitle = null;

            if (!String.IsNullOrWhiteSpace(item.Text))
            {
                if (item.Order != ToolbarItemOrder.Secondary && tintColor != null && tintColor != null)
                {
                    var             color       = item.IsEnabled ? tintColor.ToNative() : tintColor.MultiplyAlpha(0.302f).ToNative();
                    SpannableString titleTinted = new SpannableString(item.Text);
                    titleTinted.SetSpan(new ForegroundColorSpan(color), 0, titleTinted.Length(), 0);
                    newTitle = titleTinted;
                }
                else
                {
                    newTitle = new Java.Lang.String(item.Text);
                }
            }
            else
            {
                newTitle = new Java.Lang.String();
            }

            if (menuItemIndex == null || menuItemIndex >= previousMenuItems?.Count)
            {
                menuitem = menu.Add(0, AView.GenerateViewId(), 0, newTitle);
                previousMenuItems?.Add(menuitem);
            }
            else
            {
                if (previousMenuItems == null || previousMenuItems.Count < menuItemIndex.Value)
                {
                    return;
                }

                menuitem = previousMenuItems[menuItemIndex.Value];

                if (!menuitem.IsAlive())
                {
                    return;
                }

                menuitem.SetTitle(newTitle);
            }

            menuitem.SetEnabled(item.IsEnabled);
            menuitem.SetTitleOrContentDescription(item);

            if (updateMenuItemIcon != null)
            {
                updateMenuItemIcon(context, menuitem, item);
            }
            else
            {
                UpdateMenuItemIcon(mauiContext, menuitem, item, tintColor);
            }

            if (item.Order != ToolbarItemOrder.Secondary)
            {
                menuitem.SetShowAsAction(ShowAsAction.Always);
            }

            menuitem.SetOnMenuItemClickListener(new GenericMenuClickListener(((IMenuItemController)item).Activate));

            if (item.Order != ToolbarItemOrder.Secondary && !NativeVersion.IsAtLeast(26) && (tintColor != null && tintColor != null))
            {
                var view = toolbar.FindViewById(menuitem.ItemId);
                if (view is ATextView textView)
                {
                    if (item.IsEnabled)
                    {
                        textView.SetTextColor(tintColor.ToNative());
                    }
                    else
                    {
                        textView.SetTextColor(tintColor.MultiplyAlpha(0.302f).ToNative());
                    }
                }
            }
        }
コード例 #21
0
        public void OnInitializeAccessibilityNodeInfo(NativeView?host, AccessibilityNodeInfoCompat?info)
        {
            var semantics = VirtualView?.Semantics;

            if (semantics == null)
            {
                return;
            }

            if (info == null)
            {
                return;
            }

            string?newText = null;
            string?newContentDescription = null;

            var desc = semantics.Description;

            if (!string.IsNullOrEmpty(desc))
            {
                // Edit Text fields won't read anything for the content description
                if (host is EditText)
                {
                    newText = $"{desc}, {((EditText)host).Text}";
                }
                else
                {
                    newContentDescription = desc;
                }
            }

            var hint = semantics.Hint;

            if (!string.IsNullOrEmpty(hint))
            {
                // info HintText won't read anything back when using TalkBack pre API 26
                if (NativeVersion.IsAtLeast(26))
                {
                    info.HintText = hint;

                    if (host is EditText)
                    {
                        info.ShowingHintText = false;
                    }
                }
                else
                {
                    if (host is TextView tv)
                    {
                        newText = newText ?? tv.Text;
                        newText = $"{newText}, {hint}";
                    }
                    else
                    {
                        if (newContentDescription != null)
                        {
                            newText = $"{newContentDescription}, {hint}";
                        }
                        else
                        {
                            newText = $"{hint}";
                        }
                    }

                    newContentDescription = null;
                }
            }

            if (!String.IsNullOrWhiteSpace(newContentDescription))
            {
                info.ContentDescription = newContentDescription;
            }

            if (!String.IsNullOrWhiteSpace(newText))
            {
                info.Text = newText;
            }
        }