maui-linux/Xamarin.Forms.Platform.Android/VisualElementRenderer.cs

404 строки
10 KiB
C#
Исходник Обычный вид История

2016-03-22 23:02:25 +03:00
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Android.Support.V4.View;
using Android.Views;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Platform.Android.FastRenderers;
2016-03-22 23:02:25 +03:00
using AView = Android.Views.View;
namespace Xamarin.Forms.Platform.Android
{
public abstract class VisualElementRenderer<TElement> : FormsViewGroup, IVisualElementRenderer,
IEffectControlProvider where TElement : VisualElement
2016-03-22 23:02:25 +03:00
{
readonly List<EventHandler<VisualElementChangedEventArgs>> _elementChangedHandlers = new List<EventHandler<VisualElementChangedEventArgs>>();
VisualElementRendererFlags _flags = VisualElementRendererFlags.AutoPackage | VisualElementRendererFlags.AutoTrack;
string _defaultContentDescription;
bool? _defaultFocusable;
string _defaultHint;
int? _defaultLabelFor;
2016-03-22 23:02:25 +03:00
VisualElementPackager _packager;
PropertyChangedEventHandler _propertyChangeHandler;
readonly GestureManager _gestureManager;
2016-03-22 23:02:25 +03:00
protected VisualElementRenderer() : base(Forms.Context)
{
_gestureManager = new GestureManager(this);
}
public override bool OnTouchEvent(MotionEvent e)
{
return _gestureManager.OnTouchEvent(e);
}
public override bool OnInterceptTouchEvent(MotionEvent ev)
{
if (!Enabled)
{
// If Enabled is false, prevent all the events from being dispatched to child Views
// and prevent them from being processed by this View as well
return true; // IOW, intercepted
}
return base.OnInterceptTouchEvent(ev);
}
public override bool DispatchTouchEvent(MotionEvent e)
{
if (InputTransparent)
{
// If the Element is InputTransparent, this ViewGroup will be marked InputTransparent
// If we're InputTransparent we should return false on all touch events without
// even bothering to send them to the child Views
return false; // IOW, not handled
}
return base.DispatchTouchEvent(e);
2016-03-22 23:02:25 +03:00
}
public TElement Element { get; private set; }
protected bool AutoPackage
{
get { return (_flags & VisualElementRendererFlags.AutoPackage) != 0; }
set
{
if (value)
_flags |= VisualElementRendererFlags.AutoPackage;
else
_flags &= ~VisualElementRendererFlags.AutoPackage;
}
}
protected bool AutoTrack
{
get { return (_flags & VisualElementRendererFlags.AutoTrack) != 0; }
set
{
if (value)
_flags |= VisualElementRendererFlags.AutoTrack;
else
_flags &= ~VisualElementRendererFlags.AutoTrack;
}
}
View View => Element as View;
2016-03-22 23:02:25 +03:00
void IEffectControlProvider.RegisterEffect(Effect effect)
{
var platformEffect = effect as PlatformEffect;
if (platformEffect != null)
OnRegisterEffect(platformEffect);
}
VisualElement IVisualElementRenderer.Element => Element;
2016-03-22 23:02:25 +03:00
event EventHandler<VisualElementChangedEventArgs> IVisualElementRenderer.ElementChanged
{
add { _elementChangedHandlers.Add(value); }
remove { _elementChangedHandlers.Remove(value); }
}
public virtual SizeRequest GetDesiredSize(int widthConstraint, int heightConstraint)
{
Measure(widthConstraint, heightConstraint);
return new SizeRequest(new Size(MeasuredWidth, MeasuredHeight), MinimumSize());
}
void IVisualElementRenderer.SetElement(VisualElement element)
{
if (!(element is TElement))
throw new ArgumentException("element is not of type " + typeof(TElement), nameof(element));
2016-03-22 23:02:25 +03:00
SetElement((TElement)element);
}
public VisualElementTracker Tracker { get; private set; }
public void UpdateLayout()
{
Performance.Start();
Tracker?.UpdateLayout();
2016-03-22 23:02:25 +03:00
Performance.Stop();
}
public ViewGroup ViewGroup => this;
Android fastrenderers (#845) * Obsolete IVisualElementRenderer.ViewGroup in favor of .View * Fix NRE * Changing TContainer in PlatformEffect to View * Fix "View" type * new VisualElementRenderer * First attempt at a fast(er) button renderer * Fast Label Renderer * Let's try that again. Behold: Label Fast Renderer * Move FrameRenderer into Fast Renderers * Fix Disposable on VisualElementRenderer * Simplify touch and click handlers * Drop empty if clause * [Android] Add initial Image fast renderer * Split accessibility out to a separate helper class; fix tapgesture bug with label * [Android] Small fixes to VisualElementRenderer * Move accessiblity stuff to a separate class (which needs a good name) * Prevent query from looking to parent for fast renderers * [Android] ImageRenderer refactoring * Fix elevation/z-index bugs with Button (e.g., 40173) * Move SetLabeledBy to Accessibilitizer * Un-break automation IDs for Labels * Move gesture handling to its own class * Split gesture and effect management into separate classes * Remove unneeded packager from LabelRenderer * LabelRenderer inherits from FormsTextView * Batch updates to View * Fix isOnParentRenderer check for non-Android platforms * [Controls] Update Xamarin.Forms.ControlGallery.iOS.csproj * [Android,IOS] Small fixes to rebase and use of Internals * [Android] Ignroe warning for now * Fast renderers now passing InputTransparent and IsEnabled tests * Fast and legacy renderers now pass the Enabled and InputTransparent tests * Change PlatformEffect back, default container to null * Fix mangled using directives
2017-04-06 16:19:52 +03:00
AView IVisualElementRenderer.View => this;
2016-03-22 23:02:25 +03:00
public event EventHandler<ElementChangedEventArgs<TElement>> ElementChanged;
Android fastrenderers (#845) * Obsolete IVisualElementRenderer.ViewGroup in favor of .View * Fix NRE * Changing TContainer in PlatformEffect to View * Fix "View" type * new VisualElementRenderer * First attempt at a fast(er) button renderer * Fast Label Renderer * Let's try that again. Behold: Label Fast Renderer * Move FrameRenderer into Fast Renderers * Fix Disposable on VisualElementRenderer * Simplify touch and click handlers * Drop empty if clause * [Android] Add initial Image fast renderer * Split accessibility out to a separate helper class; fix tapgesture bug with label * [Android] Small fixes to VisualElementRenderer * Move accessiblity stuff to a separate class (which needs a good name) * Prevent query from looking to parent for fast renderers * [Android] ImageRenderer refactoring * Fix elevation/z-index bugs with Button (e.g., 40173) * Move SetLabeledBy to Accessibilitizer * Un-break automation IDs for Labels * Move gesture handling to its own class * Split gesture and effect management into separate classes * Remove unneeded packager from LabelRenderer * LabelRenderer inherits from FormsTextView * Batch updates to View * Fix isOnParentRenderer check for non-Android platforms * [Controls] Update Xamarin.Forms.ControlGallery.iOS.csproj * [Android,IOS] Small fixes to rebase and use of Internals * [Android] Ignroe warning for now * Fast renderers now passing InputTransparent and IsEnabled tests * Fast and legacy renderers now pass the Enabled and InputTransparent tests * Change PlatformEffect back, default container to null * Fix mangled using directives
2017-04-06 16:19:52 +03:00
public event EventHandler<PropertyChangedEventArgs> ElementPropertyChanged;
2016-03-22 23:02:25 +03:00
public void SetElement(TElement element)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
2016-03-22 23:02:25 +03:00
TElement oldElement = Element;
Element = element;
Performance.Start();
if (oldElement != null)
{
oldElement.PropertyChanged -= _propertyChangeHandler;
}
// element may be allowed to be passed as null in the future
if (element != null)
{
Color currentColor = oldElement != null ? oldElement.BackgroundColor : Color.Default;
if (element.BackgroundColor != currentColor)
UpdateBackgroundColor();
}
if (_propertyChangeHandler == null)
_propertyChangeHandler = OnElementPropertyChanged;
element.PropertyChanged += _propertyChangeHandler;
if (oldElement == null)
{
SoundEffectsEnabled = false;
}
OnElementChanged(new ElementChangedEventArgs<TElement>(oldElement, element));
if (AutoPackage && _packager == null)
SetPackager(new VisualElementPackager(this));
if (AutoTrack && Tracker == null)
SetTracker(new VisualElementTracker(this));
if (element != null)
SendVisualElementInitialized(element, this);
EffectUtilities.RegisterEffectControlProvider(this, oldElement, element);
2016-03-22 23:02:25 +03:00
if (element != null && !string.IsNullOrEmpty(element.AutomationId))
SetAutomationId(element.AutomationId);
SetContentDescription();
SetFocusable();
UpdateInputTransparent();
2016-03-22 23:02:25 +03:00
Performance.Stop();
}
/// <summary>
/// Determines whether the native control is disposed of when this renderer is disposed
/// Can be overridden in deriving classes
/// </summary>
protected virtual bool ManageNativeControlLifetime => true;
2016-03-22 23:02:25 +03:00
protected override void Dispose(bool disposing)
{
if ((_flags & VisualElementRendererFlags.Disposed) != 0)
return;
_flags |= VisualElementRendererFlags.Disposed;
if (disposing)
{
SetOnClickListener(null);
SetOnTouchListener(null);
2016-03-22 23:02:25 +03:00
if (Tracker != null)
{
Tracker.Dispose();
Tracker = null;
}
if (_packager != null)
{
_packager.Dispose();
_packager = null;
}
if (ManageNativeControlLifetime)
2016-03-22 23:02:25 +03:00
{
int count = ChildCount;
for (var i = 0; i < count; i++)
{
AView child = GetChildAt(i);
child.Dispose();
}
2016-03-22 23:02:25 +03:00
}
RemoveAllViews();
if (Element != null)
{
Element.PropertyChanged -= _propertyChangeHandler;
if (Platform.GetRenderer(Element) == this)
Platform.SetRenderer(Element, null);
Element = null;
}
}
base.Dispose(disposing);
}
protected virtual Size MinimumSize()
{
return new Size();
}
protected virtual void OnElementChanged(ElementChangedEventArgs<TElement> e)
{
var args = new VisualElementChangedEventArgs(e.OldElement, e.NewElement);
foreach (EventHandler<VisualElementChangedEventArgs> handler in _elementChangedHandlers)
handler(this, args);
2016-03-22 23:02:25 +03:00
ElementChanged?.Invoke(this, e);
2016-03-22 23:02:25 +03:00
}
protected virtual void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
UpdateBackgroundColor();
else if (e.PropertyName == AutomationProperties.HelpTextProperty.PropertyName)
SetContentDescription();
else if (e.PropertyName == AutomationProperties.NameProperty.PropertyName)
SetContentDescription();
else if (e.PropertyName == AutomationProperties.IsInAccessibleTreeProperty.PropertyName)
SetFocusable();
else if (e.PropertyName == VisualElement.InputTransparentProperty.PropertyName)
UpdateInputTransparent();
Android fastrenderers (#845) * Obsolete IVisualElementRenderer.ViewGroup in favor of .View * Fix NRE * Changing TContainer in PlatformEffect to View * Fix "View" type * new VisualElementRenderer * First attempt at a fast(er) button renderer * Fast Label Renderer * Let's try that again. Behold: Label Fast Renderer * Move FrameRenderer into Fast Renderers * Fix Disposable on VisualElementRenderer * Simplify touch and click handlers * Drop empty if clause * [Android] Add initial Image fast renderer * Split accessibility out to a separate helper class; fix tapgesture bug with label * [Android] Small fixes to VisualElementRenderer * Move accessiblity stuff to a separate class (which needs a good name) * Prevent query from looking to parent for fast renderers * [Android] ImageRenderer refactoring * Fix elevation/z-index bugs with Button (e.g., 40173) * Move SetLabeledBy to Accessibilitizer * Un-break automation IDs for Labels * Move gesture handling to its own class * Split gesture and effect management into separate classes * Remove unneeded packager from LabelRenderer * LabelRenderer inherits from FormsTextView * Batch updates to View * Fix isOnParentRenderer check for non-Android platforms * [Controls] Update Xamarin.Forms.ControlGallery.iOS.csproj * [Android,IOS] Small fixes to rebase and use of Internals * [Android] Ignroe warning for now * Fast renderers now passing InputTransparent and IsEnabled tests * Fast and legacy renderers now pass the Enabled and InputTransparent tests * Change PlatformEffect back, default container to null * Fix mangled using directives
2017-04-06 16:19:52 +03:00
ElementPropertyChanged?.Invoke(this, e);
2016-03-22 23:02:25 +03:00
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
if (Element == null)
return;
ReadOnlyCollection<Element> children = ((IElementController)Element).LogicalChildren;
UpdateLayout(((IElementController)Element).LogicalChildren);
}
static void UpdateLayout(IEnumerable<Element> children)
{
foreach (Element element in children) {
var visualElement = element as VisualElement;
2016-03-22 23:02:25 +03:00
if (visualElement == null)
continue;
IVisualElementRenderer renderer = Platform.GetRenderer(visualElement);
if (renderer == null && CompressedLayout.GetIsHeadless(visualElement))
UpdateLayout(visualElement.LogicalChildren);
2016-03-22 23:02:25 +03:00
renderer?.UpdateLayout();
}
}
protected virtual void OnRegisterEffect(PlatformEffect effect)
{
effect.SetContainer(this);
2016-03-22 23:02:25 +03:00
}
protected virtual void SetAutomationId(string id)
{
ContentDescription = id;
}
protected virtual void SetContentDescription()
{
if (Element == null)
return;
if (SetHint())
return;
if (_defaultContentDescription == null)
_defaultContentDescription = ContentDescription;
var elemValue = FastRenderers.AutomationPropertiesProvider.ConcatenateNameAndHelpText(Element);
if (!string.IsNullOrWhiteSpace(elemValue))
ContentDescription = elemValue;
else
ContentDescription = _defaultContentDescription;
}
protected virtual void SetFocusable()
{
if (Element == null)
return;
if (!_defaultFocusable.HasValue)
_defaultFocusable = Focusable;
Focusable = (bool)((bool?)Element.GetValue(AutomationProperties.IsInAccessibleTreeProperty) ?? _defaultFocusable);
}
protected virtual bool SetHint()
{
if (Element == null)
return false;
var textView = this as global::Android.Widget.TextView;
if (textView == null)
return false;
// Let the specified Title/Placeholder take precedence, but don't set the ContentDescription (won't work anyway)
if (((Element as Picker)?.Title ?? (Element as Entry)?.Placeholder ?? (Element as EntryCell)?.Placeholder) != null)
return true;
if (_defaultHint == null)
_defaultHint = textView.Hint;
var elemValue = FastRenderers.AutomationPropertiesProvider.ConcatenateNameAndHelpText(Element);
if (!string.IsNullOrWhiteSpace(elemValue))
textView.Hint = elemValue;
else
textView.Hint = _defaultHint;
return true;
}
void UpdateInputTransparent()
{
InputTransparent = Element.InputTransparent;
}
2016-03-22 23:02:25 +03:00
protected void SetPackager(VisualElementPackager packager)
{
_packager = packager;
packager.Load();
}
protected void SetTracker(VisualElementTracker tracker)
{
Tracker = tracker;
}
protected virtual void UpdateBackgroundColor()
{
SetBackgroundColor(Element.BackgroundColor.ToAndroid());
}
internal virtual void SendVisualElementInitialized(VisualElement element, AView nativeView)
{
element.SendViewInitialized(nativeView);
}
void IVisualElementRenderer.SetLabelFor(int? id)
{
if (_defaultLabelFor == null)
_defaultLabelFor = LabelFor;
LabelFor = (int)(id ?? _defaultLabelFor);
}
2016-03-22 23:02:25 +03:00
}
}