1 /* Copyright (c) 2021 Samsung Electronics Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
17 using Tizen.NUI.BaseComponents;
18 using System.Collections.Generic;
19 using System.ComponentModel;
20 using System.Diagnostics;
21 using System.Runtime.InteropServices;
22 using Tizen.NUI.Accessibility;
24 namespace Tizen.NUI.Components
27 /// ScrollEventArgs is a class to record scroll event arguments which will sent to user.
29 /// <since_tizen> 8 </since_tizen>
30 public class ScrollEventArgs : EventArgs
32 private Position position;
33 private Position scrollPosition;
36 /// Default constructor.
38 /// <param name="position">Current container position</param>
39 /// <since_tizen> 8 </since_tizen>
40 public ScrollEventArgs(Position position)
42 this.position = position;
43 this.scrollPosition = new Position(-position);
47 /// Current position of ContentContainer.
49 /// <since_tizen> 8 </since_tizen>
50 public Position Position
58 /// Current scroll position of scrollableBase pan.
59 /// This is the position in the opposite direction to the current position of ContentContainer.
61 [EditorBrowsable(EditorBrowsableState.Never)]
62 public Position ScrollPosition
66 return scrollPosition;
72 /// ScrollOutofBoundEventArgs is to record scroll out-of-bound event arguments which will be sent to user.
74 [EditorBrowsable(EditorBrowsableState.Never)]
75 public class ScrollOutOfBoundEventArgs : EventArgs
78 /// The direction to be touched.
80 [EditorBrowsable(EditorBrowsableState.Never)]
86 [EditorBrowsable(EditorBrowsableState.Never)]
92 [EditorBrowsable(EditorBrowsableState.Never)]
98 [EditorBrowsable(EditorBrowsableState.Never)]
104 [EditorBrowsable(EditorBrowsableState.Never)]
111 /// <param name="direction">Current pan direction</param>
112 /// <param name="displacement">Current total displacement</param>
113 [EditorBrowsable(EditorBrowsableState.Never)]
114 public ScrollOutOfBoundEventArgs(Direction direction, float displacement)
116 PanDirection = direction;
117 Displacement = displacement;
121 /// Current pan direction of ContentContainer.
123 [EditorBrowsable(EditorBrowsableState.Never)]
124 public Direction PanDirection
130 /// Current total displacement of ContentContainer.
131 /// if its value is greater than 0, it is at the top/left;
132 /// if less than 0, it is at the bottom/right.
134 [EditorBrowsable(EditorBrowsableState.Never)]
135 public float Displacement
142 /// This class provides a View that can scroll a single View with a layout. This View can be a nest of Views.
144 /// <since_tizen> 8 </since_tizen>
145 public partial class ScrollableBase : Control
147 static bool LayoutDebugScrollableBase = false; // Debug flag
148 private Direction mScrollingDirection = Direction.Vertical;
149 private bool mScrollEnabled = true;
150 private int mScrollDuration = 125;
151 private int mPageWidth = 0;
152 private float mPageFlickThreshold = 0.4f;
153 private float mScrollingEventThreshold = 0.001f;
155 private class ScrollableBaseCustomLayout : AbsoluteLayout
157 protected override void OnMeasure(MeasureSpecification widthMeasureSpec, MeasureSpecification heightMeasureSpec)
159 MeasuredSize.StateType childWidthState = MeasuredSize.StateType.MeasuredSizeOK;
160 MeasuredSize.StateType childHeightState = MeasuredSize.StateType.MeasuredSizeOK;
162 Direction scrollingDirection = Direction.Vertical;
163 ScrollableBase scrollableBase = this.Owner as ScrollableBase;
164 if (scrollableBase != null)
166 scrollingDirection = scrollableBase.ScrollingDirection;
169 float totalWidth = 0.0f;
170 float totalHeight = 0.0f;
172 // measure child, should be a single scrolling child
173 foreach (LayoutItem childLayout in LayoutChildren)
175 if (childLayout != null && childLayout.Owner.Name == "ContentContainer")
178 // Use an Unspecified MeasureSpecification mode so scrolling child is not restricted to it's parents size in Height (for vertical scrolling)
179 // or Width for horizontal scrolling
180 if (scrollingDirection == Direction.Vertical)
182 MeasureSpecification unrestrictedMeasureSpec = new MeasureSpecification(heightMeasureSpec.Size, MeasureSpecification.ModeType.Unspecified);
183 MeasureChildWithMargins(childLayout, widthMeasureSpec, new LayoutLength(0), unrestrictedMeasureSpec, new LayoutLength(0)); // Height unrestricted by parent
187 MeasureSpecification unrestrictedMeasureSpec = new MeasureSpecification(widthMeasureSpec.Size, MeasureSpecification.ModeType.Unspecified);
188 MeasureChildWithMargins(childLayout, unrestrictedMeasureSpec, new LayoutLength(0), heightMeasureSpec, new LayoutLength(0)); // Width unrestricted by parent
191 totalWidth = (childLayout.MeasuredWidth.Size + (childLayout.Padding.Start + childLayout.Padding.End)).AsDecimal();
192 totalHeight = (childLayout.MeasuredHeight.Size + (childLayout.Padding.Top + childLayout.Padding.Bottom)).AsDecimal();
194 if (childLayout.MeasuredWidth.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
196 childWidthState = MeasuredSize.StateType.MeasuredSizeTooSmall;
198 if (childLayout.MeasuredHeight.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
200 childHeightState = MeasuredSize.StateType.MeasuredSizeTooSmall;
205 MeasuredSize widthSizeAndState = ResolveSizeAndState(new LayoutLength(totalWidth), widthMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
206 MeasuredSize heightSizeAndState = ResolveSizeAndState(new LayoutLength(totalHeight), heightMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
207 totalWidth = widthSizeAndState.Size.AsDecimal();
208 totalHeight = heightSizeAndState.Size.AsDecimal();
210 // Ensure layout respects it's given minimum size
211 totalWidth = Math.Max(totalWidth, SuggestedMinimumWidth.AsDecimal());
212 totalHeight = Math.Max(totalHeight, SuggestedMinimumHeight.AsDecimal());
214 widthSizeAndState.State = childWidthState;
215 heightSizeAndState.State = childHeightState;
217 SetMeasuredDimensions(ResolveSizeAndState(new LayoutLength(totalWidth), widthMeasureSpec, childWidthState),
218 ResolveSizeAndState(new LayoutLength(totalHeight), heightMeasureSpec, childHeightState));
220 // Size of ScrollableBase is changed. Change Page width too.
221 if (scrollableBase != null)
223 scrollableBase.mPageWidth = (int)MeasuredWidth.Size.AsRoundedValue();
224 scrollableBase.OnScrollingChildRelayout(null, null);
227 } // ScrollableBaseCustomLayout
230 /// The direction axis to scroll.
232 /// <since_tizen> 8 </since_tizen>
233 public enum Direction
238 /// <since_tizen> 8 </since_tizen>
244 /// <since_tizen> 8 </since_tizen>
249 /// Scrolling direction mode.
250 /// Default is Vertical scrolling.
252 /// <since_tizen> 8 </since_tizen>
253 public Direction ScrollingDirection
257 return (Direction)GetValue(ScrollingDirectionProperty);
261 SetValue(ScrollingDirectionProperty, value);
262 NotifyPropertyChanged();
265 private Direction InternalScrollingDirection
269 return mScrollingDirection;
273 if (value != mScrollingDirection)
275 //Reset scroll position and stop scroll animation
278 mScrollingDirection = value;
279 mPanGestureDetector.ClearAngles();
280 mPanGestureDetector.AddDirection(value == Direction.Horizontal ?
281 PanGestureDetector.DirectionHorizontal : PanGestureDetector.DirectionVertical);
283 ContentContainer.WidthSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.MatchParent : LayoutParamPolicies.WrapContent;
284 ContentContainer.HeightSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.WrapContent : LayoutParamPolicies.MatchParent;
291 /// Enable or disable scrolling.
293 /// <since_tizen> 8 </since_tizen>
294 public bool ScrollEnabled
298 return (bool)GetValue(ScrollEnabledProperty);
302 SetValue(ScrollEnabledProperty, value);
303 NotifyPropertyChanged();
306 private bool InternalScrollEnabled
310 return mScrollEnabled;
314 if (value != mScrollEnabled)
316 mScrollEnabled = value;
319 mPanGestureDetector.Detected += OnPanGestureDetected;
323 mPanGestureDetector.Detected -= OnPanGestureDetected;
330 /// Gets scrollable status.
332 [EditorBrowsable(EditorBrowsableState.Never)]
333 protected override bool AccessibilityIsScrollable()
339 /// Pages mode, enables moving to the next or return to current page depending on pan displacement.
340 /// Default is false.
342 /// <since_tizen> 8 </since_tizen>
343 public bool SnapToPage
347 return (bool)GetValue(SnapToPageProperty);
351 SetValue(SnapToPageProperty, value);
352 NotifyPropertyChanged();
355 private bool InternalSnapToPage { set; get; } = false;
358 /// Get current page.
359 /// Working property with SnapToPage property.
361 /// <since_tizen> 8 </since_tizen>
362 public int CurrentPage { get; private set; } = 0;
365 /// Duration of scroll animation.
366 /// Default value is 125ms.
368 /// <since_tizen> 8 </since_tizen>
369 public int ScrollDuration
373 return (int)GetValue(ScrollDurationProperty);
377 SetValue(ScrollDurationProperty, value);
378 NotifyPropertyChanged();
381 private int InternalScrollDuration
385 mScrollDuration = value >= 0 ? value : mScrollDuration;
389 return mScrollDuration;
394 /// Scroll Available area.
396 /// <since_tizen> 8 </since_tizen>
397 public Vector2 ScrollAvailableArea
401 return GetValue(ScrollAvailableAreaProperty) as Vector2;
405 SetValue(ScrollAvailableAreaProperty, value);
406 NotifyPropertyChanged();
409 private Vector2 InternalScrollAvailableArea { set; get; }
412 /// An event emitted when user starts dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
414 /// <since_tizen> 8 </since_tizen>
415 public event EventHandler<ScrollEventArgs> ScrollDragStarted;
418 /// An event emitted when user stops dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
420 /// <since_tizen> 8 </since_tizen>
421 public event EventHandler<ScrollEventArgs> ScrollDragEnded;
424 /// An event emitted when the scrolling slide animation starts, user can subscribe or unsubscribe to this event handler.<br />
426 /// <since_tizen> 8 </since_tizen>
427 public event EventHandler<ScrollEventArgs> ScrollAnimationStarted;
430 /// An event emitted when the scrolling slide animation ends, user can subscribe or unsubscribe to this event handler.<br />
432 /// <since_tizen> 8 </since_tizen>
433 public event EventHandler<ScrollEventArgs> ScrollAnimationEnded;
436 /// An event emitted when scrolling, user can subscribe or unsubscribe to this event handler.<br />
438 /// <since_tizen> 8 </since_tizen>
439 public event EventHandler<ScrollEventArgs> Scrolling;
442 /// An event emitted when scrolling out of bound, user can subscribe or unsubscribe to this event handler.<br />
444 [EditorBrowsable(EditorBrowsableState.Never)]
445 public event EventHandler<ScrollOutOfBoundEventArgs> ScrollOutOfBound;
448 /// Scrollbar for ScrollableBase.
450 /// <since_tizen> 8 </since_tizen>
451 public ScrollbarBase Scrollbar
455 return GetValue(ScrollbarProperty) as ScrollbarBase;
459 SetValue(ScrollbarProperty, value);
460 NotifyPropertyChanged();
463 private ScrollbarBase InternalScrollbar
473 base.Remove(scrollBar);
477 if (scrollBar != null)
479 scrollBar.Name = "ScrollBar";
497 /// Always hide Scrollbar.
499 /// <since_tizen> 8 </since_tizen>
500 public bool HideScrollbar
504 return (bool)GetValue(HideScrollbarProperty);
508 SetValue(HideScrollbarProperty, value);
509 NotifyPropertyChanged();
512 private bool InternalHideScrollbar
516 return hideScrollbar;
520 hideScrollbar = value;
537 /// Container which has content of ScrollableBase.
539 /// <since_tizen> 8 </since_tizen>
540 public View ContentContainer { get; private set; }
543 /// Set the layout on this View. Replaces any existing Layout.
545 /// <since_tizen> 8 </since_tizen>
546 public new LayoutItem Layout
550 return GetValue(LayoutProperty) as LayoutItem;
554 SetValue(LayoutProperty, value);
555 NotifyPropertyChanged();
558 private LayoutItem InternalLayout
562 return ContentContainer.Layout;
566 ContentContainer.Layout = value;
571 /// List of children of Container.
573 /// <since_tizen> 8 </since_tizen>
574 public new List<View> Children
578 return ContentContainer.Children;
583 /// Deceleration rate of scrolling by finger.
584 /// Rate should be bigger than 0 and smaller than 1.
585 /// Default value is 0.998f;
587 /// <since_tizen> 8 </since_tizen>
588 public float DecelerationRate
592 return (float)GetValue(DecelerationRateProperty);
596 SetValue(DecelerationRateProperty, value);
597 NotifyPropertyChanged();
600 private float InternalDecelerationRate
604 return decelerationRate;
608 decelerationRate = (value < 1 && value > 0) ? value : decelerationRate;
609 logValueOfDeceleration = (float)Math.Log(value);
614 /// Threshold not to go infinite at the end of scrolling animation.
616 [EditorBrowsable(EditorBrowsableState.Never)]
617 public float DecelerationThreshold
621 return (float)GetValue(DecelerationThresholdProperty);
625 SetValue(DecelerationThresholdProperty, value);
626 NotifyPropertyChanged();
629 private float InternalDecelerationThreshold { get; set; } = 0.1f;
632 /// Scrolling event will be thrown when this amount of scroll position is changed.
633 /// If this threshold becomes smaller, the tracking detail increases but the scrolling range that can be tracked becomes smaller.
634 /// If large sized ContentContainer is required, please use larger threshold value.
635 /// Default ScrollingEventThreshold value is 0.001f.
637 [EditorBrowsable(EditorBrowsableState.Never)]
638 public float ScrollingEventThreshold
642 return (float)GetValue(ScrollingEventThresholdProperty);
646 SetValue(ScrollingEventThresholdProperty, value);
647 NotifyPropertyChanged();
650 private float InternalScrollingEventThreshold
654 return mScrollingEventThreshold;
658 if (mScrollingEventThreshold != value && value > 0)
660 ContentContainer.RemovePropertyNotification(propertyNotification);
661 propertyNotification = ContentContainer.AddPropertyNotification("position", PropertyCondition.Step(value));
662 propertyNotification.Notified += OnPropertyChanged;
663 mScrollingEventThreshold = value;
669 /// Page will be changed when velocity of panning is over threshold.
670 /// The unit of threshold is pixel per millisecond.
672 /// <since_tizen> 8 </since_tizen>
673 public float PageFlickThreshold
677 return (float)GetValue(PageFlickThresholdProperty);
681 SetValue(PageFlickThresholdProperty, value);
682 NotifyPropertyChanged();
685 private float InternalPageFlickThreshold
689 return mPageFlickThreshold;
693 mPageFlickThreshold = value >= 0f ? value : mPageFlickThreshold;
698 /// Padding for the ScrollableBase
700 [EditorBrowsable(EditorBrowsableState.Never)]
701 public new Extents Padding
705 return GetValue(PaddingProperty) as Extents;
709 SetValue(PaddingProperty, value);
710 NotifyPropertyChanged();
713 private Extents InternalPadding
717 return ContentContainer.Padding;
721 ContentContainer.Padding = value;
726 /// Alphafunction for scroll animation.
728 [EditorBrowsable(EditorBrowsableState.Never)]
729 public AlphaFunction ScrollAlphaFunction
733 return GetValue(ScrollAlphaFunctionProperty) as AlphaFunction;
737 SetValue(ScrollAlphaFunctionProperty, value);
738 NotifyPropertyChanged();
741 private AlphaFunction InternalScrollAlphaFunction { get; set; } = new AlphaFunction(AlphaFunction.BuiltinFunctions.Linear);
743 private bool hideScrollbar = true;
744 private float maxScrollDistance;
745 private float childTargetPosition = 0.0f;
746 private PanGestureDetector mPanGestureDetector;
747 private ScrollbarBase scrollBar;
748 private bool scrolling = false;
749 private float ratioOfScreenWidthToCompleteScroll = 0.5f;
750 private float totalDisplacementForPan = 0.0f;
751 private Size previousContainerSize = new Size();
752 private Size previousSize = new Size();
753 private PropertyNotification propertyNotification;
754 private float noticeAnimationEndBeforePosition = 0.0f;
755 private bool readyToNotice = false;
758 /// Notice before animation is finished.
760 [EditorBrowsable(EditorBrowsableState.Never)]
761 // Let's consider more whether this needs to be set as protected.
762 public float NoticeAnimationEndBeforePosition
766 return (float)GetValue(NoticeAnimationEndBeforePositionProperty);
770 SetValue(NoticeAnimationEndBeforePositionProperty, value);
771 NotifyPropertyChanged();
774 private float InternalNoticeAnimationEndBeforePosition
776 get => noticeAnimationEndBeforePosition;
777 set => noticeAnimationEndBeforePosition = value;
780 // Let's consider more whether this needs to be set as protected.
781 private float finalTargetPosition;
783 private Animation scrollAnimation;
784 // Declare user alpha function delegate
785 [UnmanagedFunctionPointer(CallingConvention.StdCall)]
786 private delegate float UserAlphaFunctionDelegate(float progress);
787 private UserAlphaFunctionDelegate customScrollAlphaFunction;
788 private float velocityOfLastPan = 0.0f;
789 private float panAnimationDuration = 0.0f;
790 private float panAnimationDelta = 0.0f;
791 private float logValueOfDeceleration = 0.0f;
792 private float decelerationRate = 0.0f;
794 private View topOverShootingShadowView;
795 private View bottomOverShootingShadowView;
796 private View leftOverShootingShadowView;
797 private View rightOverShootingShadowView;
798 private const int overShootingShadowScaleHeightLimit = 64 * 3;
799 private const int overShootingShadowAnimationDuration = 300;
800 private Animation overShootingShadowAnimation;
801 private bool isOverShootingShadowShown = false;
802 private float startShowShadowDisplacement;
805 /// Default Constructor
807 /// <since_tizen> 8 </since_tizen>
808 public ScrollableBase() : base()
810 DecelerationRate = 0.998f;
812 base.Layout = new ScrollableBaseCustomLayout();
813 mPanGestureDetector = new PanGestureDetector();
814 mPanGestureDetector.Attach(this);
815 mPanGestureDetector.AddDirection(PanGestureDetector.DirectionVertical);
816 if (mPanGestureDetector.GetMaximumTouchesRequired() < 2) mPanGestureDetector.SetMaximumTouchesRequired(2);
817 mPanGestureDetector.Detected += OnPanGestureDetected;
819 ClippingMode = ClippingModeType.ClipToBoundingBox;
821 //Default Scrolling child
822 ContentContainer = new View()
824 Name = "ContentContainer",
825 WidthSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.MatchParent : LayoutParamPolicies.WrapContent,
826 HeightSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.WrapContent : LayoutParamPolicies.MatchParent,
828 // Check if children's sizes change to update Scrollbar
829 ContentContainer.Relayout += OnScrollingChildRelayout;
830 propertyNotification = ContentContainer.AddPropertyNotification("position", PropertyCondition.Step(mScrollingEventThreshold));
831 propertyNotification.Notified += OnPropertyChanged;
832 base.Add(ContentContainer);
833 // Check if ScrollableBase's size changes to update Scrollbar
834 base.Relayout += OnScrollingChildRelayout;
836 Scrollbar = new Scrollbar();
838 //Show vertical shadow on the top (or bottom) of the scrollable when panning down (or up).
839 topOverShootingShadowView = new View
841 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_top.png",
844 PositionUsesPivotPoint = true,
845 ParentOrigin = NUI.ParentOrigin.TopCenter,
846 PivotPoint = NUI.PivotPoint.TopCenter,
848 bottomOverShootingShadowView = new View
850 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_bottom.png",
853 PositionUsesPivotPoint = true,
854 ParentOrigin = NUI.ParentOrigin.BottomCenter,
855 PivotPoint = NUI.PivotPoint.BottomCenter,
857 //Show horizontal shadow on the left (or right) of the scrollable when panning down (or up).
858 leftOverShootingShadowView = new View
860 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_left.png",
863 PositionUsesPivotPoint = true,
864 ParentOrigin = NUI.ParentOrigin.CenterLeft,
865 PivotPoint = NUI.PivotPoint.CenterLeft,
867 rightOverShootingShadowView = new View
869 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_right.png",
872 PositionUsesPivotPoint = true,
873 ParentOrigin = NUI.ParentOrigin.CenterRight,
874 PivotPoint = NUI.PivotPoint.CenterRight,
877 AccessibilityManager.Instance.SetAccessibilityAttribute(this, AccessibilityManager.AccessibilityAttribute.Trait, "ScrollableBase");
879 SetKeyboardNavigationSupport(true);
882 private bool OnInterruptTouchingChildTouched(object source, View.TouchEventArgs args)
884 if (args.Touch.GetState(0) == PointStateType.Down)
886 if (scrolling && !SnapToPage)
894 private void OnPropertyChanged(object source, PropertyNotification.NotifyEventArgs args)
900 /// Called after a child has been added to the owning view.
902 /// <param name="view">The child which has been added.</param>
903 /// <since_tizen> 8 </since_tizen>
904 public override void Add(View view)
906 ContentContainer.Add(view);
910 /// Called after a child has been removed from the owning view.
912 /// <param name="view">The child which has been removed.</param>
913 /// <since_tizen> 8 </since_tizen>
914 public override void Remove(View view)
916 if (SnapToPage && CurrentPage == Children.IndexOf(view) && CurrentPage == Children.Count - 1 && Children.Count > 1)
918 // Target View is current page and also last child.
919 // CurrentPage should be changed to previous page.
920 ScrollToIndex(CurrentPage - 1);
923 ContentContainer.Remove(view);
926 private void OnScrollingChildRelayout(object source, EventArgs args)
928 // Size is changed. Calculate maxScrollDistance.
929 bool isSizeChanged = previousContainerSize.Width != ContentContainer.Size.Width || previousContainerSize.Height != ContentContainer.Size.Height ||
930 previousSize.Width != Size.Width || previousSize.Height != Size.Height;
934 maxScrollDistance = CalculateMaximumScrollDistance();
935 if (!ReviseContainerPositionIfNeed())
941 previousContainerSize = new Size(ContentContainer.Size);
942 previousSize = new Size(Size);
945 private bool ReviseContainerPositionIfNeed()
947 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
948 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
950 if (Math.Abs(currentPosition) > maxScrollDistance)
953 var targetPosition = BoundScrollPosition(-maxScrollDistance);
954 if (isHorizontal) ContentContainer.PositionX = targetPosition;
955 else ContentContainer.PositionY = targetPosition;
963 /// The composition of a Scrollbar can vary depending on how you use ScrollableBase.
964 /// Set the composition that will go into the ScrollableBase according to your ScrollableBase.
966 /// <since_tizen> 8 </since_tizen>
967 [EditorBrowsable(EditorBrowsableState.Never)]
968 protected virtual void SetScrollbar()
972 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
973 float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
974 float viewportLength = isHorizontal ? Size.Width : Size.Height;
975 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
976 Scrollbar.Initialize(contentLength, viewportLength, -currentPosition, isHorizontal);
980 /// Update scrollbar position and size.
981 [EditorBrowsable(EditorBrowsableState.Never)]
982 protected virtual void UpdateScrollbar()
986 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
987 float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
988 float viewportLength = isHorizontal ? Size.Width : Size.Height;
989 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
990 Scrollbar.Update(contentLength, viewportLength, -currentPosition);
995 /// Scrolls to the item at the specified index.
997 /// <param name="index">Index of item.</param>
998 /// <since_tizen> 8 </since_tizen>
999 public void ScrollToIndex(int index)
1001 if (ContentContainer.ChildCount - 1 < index || index < 0)
1008 CurrentPage = index;
1011 float targetPosition = Math.Min(ScrollingDirection == Direction.Vertical ? Children[index].Position.Y : Children[index].Position.X, maxScrollDistance);
1012 AnimateChildTo(ScrollDuration, -targetPosition);
1015 private void OnScrollDragStarted()
1017 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1018 ScrollDragStarted?.Invoke(this, eventArgs);
1021 private void OnScrollDragEnded()
1023 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1024 ScrollDragEnded?.Invoke(this, eventArgs);
1027 private void OnScrollAnimationStarted()
1029 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1030 ScrollAnimationStarted?.Invoke(this, eventArgs);
1033 private void OnScrollAnimationEnded()
1036 this.InterceptTouchEvent -= OnInterruptTouchingChildTouched;
1038 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1039 ScrollAnimationEnded?.Invoke(this, eventArgs);
1042 private void OnScroll()
1044 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1045 Scrolling?.Invoke(this, eventArgs);
1047 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
1048 float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
1049 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
1051 scrollBar?.Update(contentLength, Math.Abs(currentPosition));
1052 CheckPreReachedTargetPosition();
1055 private void CheckPreReachedTargetPosition()
1057 // Check whether we reached pre-reached target position
1058 if (readyToNotice &&
1059 ContentContainer.CurrentPosition.Y <= finalTargetPosition + NoticeAnimationEndBeforePosition &&
1060 ContentContainer.CurrentPosition.Y >= finalTargetPosition - NoticeAnimationEndBeforePosition)
1063 readyToNotice = false;
1064 OnPreReachedTargetPosition(finalTargetPosition);
1069 /// This helps developer who wants to know before scroll is reaching target position.
1071 /// <param name="targetPosition">Index of item.</param>
1072 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
1073 [EditorBrowsable(EditorBrowsableState.Never)]
1074 protected virtual void OnPreReachedTargetPosition(float targetPosition)
1079 private void StopScroll()
1081 if (scrollAnimation != null)
1083 if (scrollAnimation.State == Animation.States.Playing)
1085 Debug.WriteLineIf(LayoutDebugScrollableBase, "StopScroll Animation Playing");
1086 scrollAnimation.Stop(Animation.EndActions.Cancel);
1087 OnScrollAnimationEnded();
1089 scrollAnimation.Clear();
1093 private void AnimateChildTo(int duration, float axisPosition)
1095 Debug.WriteLineIf(LayoutDebugScrollableBase, "AnimationTo Animation Duration:" + duration + " Destination:" + axisPosition);
1096 finalTargetPosition = axisPosition;
1098 StopScroll(); // Will replace previous animation so will stop existing one.
1100 if (scrollAnimation == null)
1102 scrollAnimation = new Animation();
1103 scrollAnimation.Finished += ScrollAnimationFinished;
1106 scrollAnimation.Duration = duration;
1107 scrollAnimation.DefaultAlphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.EaseOutSquare);
1108 scrollAnimation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", axisPosition, ScrollAlphaFunction);
1110 OnScrollAnimationStarted();
1111 scrollAnimation.Play();
1115 /// Scroll to specific position with or without animation.
1117 /// <param name="position">Destination.</param>
1118 /// <param name="animate">Scroll with or without animation</param>
1119 /// <since_tizen> 8 </since_tizen>
1120 public void ScrollTo(float position, bool animate)
1123 float currentPositionX = ContentContainer.CurrentPosition.X != 0 ? ContentContainer.CurrentPosition.X : ContentContainer.Position.X;
1124 float currentPositionY = ContentContainer.CurrentPosition.Y != 0 ? ContentContainer.CurrentPosition.Y : ContentContainer.Position.Y;
1125 float delta = ScrollingDirection == Direction.Horizontal ? currentPositionX : currentPositionY;
1126 // The argument position is the new pan position. So the new position of ScrollableBase becomes (-position).
1127 // To move ScrollableBase's position to (-position), it moves by (-position - currentPosition).
1128 delta = -position - delta;
1130 ScrollBy(delta, animate);
1133 private float BoundScrollPosition(float targetPosition)
1135 if (ScrollAvailableArea != null)
1137 float minScrollPosition = ScrollAvailableArea.X;
1138 float maxScrollPosition = ScrollAvailableArea.Y;
1140 targetPosition = Math.Min(-minScrollPosition, targetPosition);
1141 targetPosition = Math.Max(-maxScrollPosition, targetPosition);
1145 targetPosition = Math.Min(0, targetPosition);
1146 targetPosition = Math.Max(-maxScrollDistance, targetPosition);
1149 return targetPosition;
1152 private void ScrollBy(float displacement, bool animate)
1154 if (GetChildCount() == 0 || maxScrollDistance < 0)
1159 float childCurrentPosition = (ScrollingDirection == Direction.Horizontal) ? ContentContainer.PositionX : ContentContainer.PositionY;
1161 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy childCurrentPosition:" + childCurrentPosition +
1162 " displacement:" + displacement,
1163 " maxScrollDistance:" + maxScrollDistance);
1165 childTargetPosition = childCurrentPosition + displacement; // child current position + gesture displacement
1167 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy currentAxisPosition:" + childCurrentPosition + "childTargetPosition:" + childTargetPosition);
1171 // Calculate scroll animation duration
1172 float scrollDistance = Math.Abs(displacement);
1173 readyToNotice = true;
1175 AnimateChildTo(ScrollDuration, BoundScrollPosition(AdjustTargetPositionOfScrollAnimation(BoundScrollPosition(childTargetPosition))));
1180 finalTargetPosition = BoundScrollPosition(childTargetPosition);
1182 // Set position of scrolling child without an animation
1183 if (ScrollingDirection == Direction.Horizontal)
1185 ContentContainer.PositionX = finalTargetPosition;
1189 ContentContainer.PositionY = finalTargetPosition;
1195 /// you can override it to clean-up your own resources.
1197 /// <param name="type">DisposeTypes</param>
1198 /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
1199 [EditorBrowsable(EditorBrowsableState.Never)]
1200 protected override void Dispose(DisposeTypes type)
1207 if (type == DisposeTypes.Explicit)
1209 StopOverShootingShadowAnimation();
1212 if (mPanGestureDetector != null)
1214 mPanGestureDetector.Detected -= OnPanGestureDetected;
1215 mPanGestureDetector.Dispose();
1216 mPanGestureDetector = null;
1219 propertyNotification.Dispose();
1224 private float CalculateMaximumScrollDistance()
1226 float scrollingChildLength = 0;
1227 float scrollerLength = 0;
1228 if (ScrollingDirection == Direction.Horizontal)
1230 Debug.WriteLineIf(LayoutDebugScrollableBase, "Horizontal");
1232 scrollingChildLength = ContentContainer.Size.Width;
1233 scrollerLength = Size.Width;
1237 Debug.WriteLineIf(LayoutDebugScrollableBase, "Vertical");
1238 scrollingChildLength = ContentContainer.Size.Height;
1239 scrollerLength = Size.Height;
1242 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy maxScrollDistance:" + (scrollingChildLength - scrollerLength) +
1243 " parent length:" + scrollerLength +
1244 " scrolling child length:" + scrollingChildLength);
1246 return Math.Max(scrollingChildLength - scrollerLength, 0);
1249 private void PageSnap(float velocity)
1253 Debug.WriteLineIf(LayoutDebugScrollableBase, "PageSnap with pan candidate totalDisplacement:" + totalDisplacementForPan +
1254 " currentPage[" + CurrentPage + "]");
1256 //Increment current page if total displacement enough to warrant a page change.
1257 if (Math.Abs(totalDisplacementForPan) > (mPageWidth * ratioOfScreenWidthToCompleteScroll))
1259 if (totalDisplacementForPan < 0)
1261 CurrentPage = Math.Min(Math.Max(Children.Count - 1, 0), ++CurrentPage);
1265 CurrentPage = Math.Max(0, --CurrentPage);
1268 else if (Math.Abs(velocity) > PageFlickThreshold)
1272 CurrentPage = Math.Min(Math.Max(Children.Count - 1, 0), ++CurrentPage);
1276 CurrentPage = Math.Max(0, --CurrentPage);
1280 // Animate to new page or reposition to current page
1281 if (ScrollingDirection == Direction.Horizontal)
1282 destination = -(Children[CurrentPage].Position.X + Children[CurrentPage].CurrentSize.Width / 2 - CurrentSize.Width / 2); // set to middle of current page
1284 destination = -(Children[CurrentPage].Position.Y + Children[CurrentPage].CurrentSize.Height / 2 - CurrentSize.Height / 2);
1286 AnimateChildTo(ScrollDuration, destination);
1290 /// Enable/Disable overshooting effect. default is disabled.
1292 [EditorBrowsable(EditorBrowsableState.Never)]
1293 public bool EnableOverShootingEffect
1297 return (bool)GetValue(EnableOverShootingEffectProperty);
1301 SetValue(EnableOverShootingEffectProperty, value);
1302 NotifyPropertyChanged();
1305 private bool InternalEnableOverShootingEffect { get; set; } = false;
1307 private void AttachOverShootingShadowView()
1309 if (!EnableOverShootingEffect)
1312 // stop animation if necessary.
1313 StopOverShootingShadowAnimation();
1315 if (ScrollingDirection == Direction.Horizontal)
1317 base.Add(leftOverShootingShadowView);
1318 base.Add(rightOverShootingShadowView);
1320 leftOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1321 leftOverShootingShadowView.Opacity = 1.0f;
1322 leftOverShootingShadowView.RaiseToTop();
1324 rightOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1325 rightOverShootingShadowView.Opacity = 1.0f;
1326 rightOverShootingShadowView.RaiseToTop();
1330 base.Add(topOverShootingShadowView);
1331 base.Add(bottomOverShootingShadowView);
1333 topOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1334 topOverShootingShadowView.Opacity = 1.0f;
1335 topOverShootingShadowView.RaiseToTop();
1337 bottomOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1338 bottomOverShootingShadowView.Opacity = 1.0f;
1339 bottomOverShootingShadowView.RaiseToTop();
1342 // at the beginning, height or width of overshooting shadow is 0, so it is invisible.
1343 isOverShootingShadowShown = false;
1346 private void DragOverShootingShadow(float totalPanDisplacement, float panDisplacement)
1348 if (!EnableOverShootingEffect)
1351 if (totalPanDisplacement > 0) // downwards
1353 // check if reaching at the top / left.
1354 if ((int)finalTargetPosition != 0)
1356 isOverShootingShadowShown = false;
1360 // save start displacement, and re-calculate displacement.
1361 if (!isOverShootingShadowShown)
1363 startShowShadowDisplacement = totalPanDisplacement;
1365 isOverShootingShadowShown = true;
1367 float newDisplacement = (int)totalPanDisplacement < (int)startShowShadowDisplacement ? 0 : totalPanDisplacement - startShowShadowDisplacement;
1369 if (ScrollingDirection == Direction.Horizontal)
1371 // scale limit of height is 60%.
1372 float heightScale = newDisplacement / overShootingShadowScaleHeightLimit;
1373 leftOverShootingShadowView.SizeHeight = heightScale > 0.6f ? SizeHeight * 0.4f : SizeHeight * (1.0f - heightScale);
1375 // scale limit of width is 300%.
1376 leftOverShootingShadowView.SizeWidth = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1379 ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1380 ScrollOutOfBoundEventArgs.Direction.Right : ScrollOutOfBoundEventArgs.Direction.Left;
1381 OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1385 // scale limit of width is 60%.
1386 float widthScale = newDisplacement / overShootingShadowScaleHeightLimit;
1387 topOverShootingShadowView.SizeWidth = widthScale > 0.6f ? SizeWidth * 0.4f : SizeWidth * (1.0f - widthScale);
1389 // scale limit of height is 300%.
1390 topOverShootingShadowView.SizeHeight = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1393 ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1394 ScrollOutOfBoundEventArgs.Direction.Down : ScrollOutOfBoundEventArgs.Direction.Up;
1395 OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1398 else if (totalPanDisplacement < 0) // upwards
1400 // check if reaching at the bottom.
1401 if (-(int)finalTargetPosition != (int)maxScrollDistance)
1403 isOverShootingShadowShown = false;
1407 // save start displacement, and re-calculate displacement.
1408 if (!isOverShootingShadowShown)
1410 startShowShadowDisplacement = totalPanDisplacement;
1412 isOverShootingShadowShown = true;
1414 float newDisplacement = (int)startShowShadowDisplacement < (int)totalPanDisplacement ? 0 : startShowShadowDisplacement - totalPanDisplacement;
1416 if (ScrollingDirection == Direction.Horizontal)
1418 // scale limit of height is 60%.
1419 float heightScale = newDisplacement / overShootingShadowScaleHeightLimit;
1420 rightOverShootingShadowView.SizeHeight = heightScale > 0.6f ? SizeHeight * 0.4f : SizeHeight * (1.0f - heightScale);
1422 // scale limit of width is 300%.
1423 rightOverShootingShadowView.SizeWidth = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1426 ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1427 ScrollOutOfBoundEventArgs.Direction.Right : ScrollOutOfBoundEventArgs.Direction.Left;
1428 OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1432 // scale limit of width is 60%.
1433 float widthScale = newDisplacement / overShootingShadowScaleHeightLimit;
1434 bottomOverShootingShadowView.SizeWidth = widthScale > 0.6f ? SizeWidth * 0.4f : SizeWidth * (1.0f - widthScale);
1436 // scale limit of height is 300%.
1437 bottomOverShootingShadowView.SizeHeight = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1440 ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1441 ScrollOutOfBoundEventArgs.Direction.Down : ScrollOutOfBoundEventArgs.Direction.Up;
1442 OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1447 // if total displacement is 0, shadow would become invisible.
1448 isOverShootingShadowShown = false;
1452 private void PlayOverShootingShadowAnimation()
1454 if (!EnableOverShootingEffect)
1457 // stop animation if necessary.
1458 StopOverShootingShadowAnimation();
1460 if (overShootingShadowAnimation == null)
1462 overShootingShadowAnimation = new Animation(overShootingShadowAnimationDuration);
1463 overShootingShadowAnimation.Finished += OnOverShootingShadowAnimationFinished;
1466 if (ScrollingDirection == Direction.Horizontal)
1468 View targetView = totalDisplacementForPan < 0 ? rightOverShootingShadowView : leftOverShootingShadowView;
1469 overShootingShadowAnimation.AnimateTo(targetView, "SizeHeight", SizeHeight);
1470 overShootingShadowAnimation.AnimateTo(targetView, "SizeWidth", 0.0f);
1471 overShootingShadowAnimation.AnimateTo(targetView, "Opacity", 0.0f);
1475 View targetView = totalDisplacementForPan < 0 ? bottomOverShootingShadowView : topOverShootingShadowView;
1476 overShootingShadowAnimation.AnimateTo(targetView, "SizeWidth", SizeWidth);
1477 overShootingShadowAnimation.AnimateTo(targetView, "SizeHeight", 0.0f);
1478 overShootingShadowAnimation.AnimateTo(targetView, "Opacity", 0.0f);
1480 overShootingShadowAnimation.Play();
1483 private void StopOverShootingShadowAnimation()
1485 if (overShootingShadowAnimation == null || overShootingShadowAnimation.State != Animation.States.Playing)
1488 overShootingShadowAnimation.Stop(Animation.EndActions.Cancel);
1489 OnOverShootingShadowAnimationFinished(null, null);
1490 overShootingShadowAnimation.Clear();
1493 private void OnOverShootingShadowAnimationFinished(object sender, EventArgs e)
1495 if (ScrollingDirection == Direction.Horizontal)
1497 base.Remove(leftOverShootingShadowView);
1498 base.Remove(rightOverShootingShadowView);
1500 leftOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1501 rightOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1505 base.Remove(topOverShootingShadowView);
1506 base.Remove(bottomOverShootingShadowView);
1508 topOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1509 bottomOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1512 // after animation finished, height/width & opacity of vertical shadow both are 0, so it is invisible.
1513 isOverShootingShadowShown = false;
1516 private void OnScrollOutOfBound(ScrollOutOfBoundEventArgs.Direction direction, float displacement)
1518 ScrollOutOfBoundEventArgs args = new ScrollOutOfBoundEventArgs(direction, displacement);
1519 ScrollOutOfBound?.Invoke(this, args);
1522 private void OnPanGestureDetected(object source, PanGestureDetector.DetectedEventArgs e)
1524 e.Handled = OnPanGesture(e.PanGesture);
1527 private bool OnPanGesture(PanGesture panGesture)
1529 bool handled = true;
1530 if (SnapToPage && scrollAnimation != null && scrollAnimation.State == Animation.States.Playing)
1534 if (panGesture.State == Gesture.StateType.Started)
1536 readyToNotice = false;
1537 AttachOverShootingShadowView();
1538 Debug.WriteLineIf(LayoutDebugScrollableBase, "Gesture Start");
1539 if (scrolling && !SnapToPage)
1543 totalDisplacementForPan = 0.0f;
1545 // check if gesture need to propagation
1546 var checkDisplacement = (ScrollingDirection == Direction.Horizontal) ? panGesture.Displacement.X : panGesture.Displacement.Y;
1547 var checkChildCurrentPosition = (ScrollingDirection == Direction.Horizontal) ? ContentContainer.PositionX : ContentContainer.PositionY;
1548 var checkChildTargetPosition = checkChildCurrentPosition + checkDisplacement;
1549 var checkFinalTargetPosition = BoundScrollPosition(checkChildTargetPosition);
1550 handled = !((int)checkFinalTargetPosition == 0 || -(int)checkFinalTargetPosition == (int)maxScrollDistance);
1551 // If you propagate a gesture event, return;
1557 //Interrupt touching when panning is started
1558 this.InterceptTouchEvent += OnInterruptTouchingChildTouched;
1559 OnScrollDragStarted();
1561 else if (panGesture.State == Gesture.StateType.Continuing)
1563 if (ScrollingDirection == Direction.Horizontal)
1565 // if vertical shadow is shown, does not scroll.
1566 if (!isOverShootingShadowShown)
1568 ScrollBy(panGesture.Displacement.X, false);
1570 totalDisplacementForPan += panGesture.Displacement.X;
1571 DragOverShootingShadow(totalDisplacementForPan, panGesture.Displacement.X);
1575 // if vertical shadow is shown, does not scroll.
1576 if (!isOverShootingShadowShown)
1578 ScrollBy(panGesture.Displacement.Y, false);
1580 totalDisplacementForPan += panGesture.Displacement.Y;
1581 DragOverShootingShadow(totalDisplacementForPan, panGesture.Displacement.Y);
1583 Debug.WriteLineIf(LayoutDebugScrollableBase, "OnPanGestureDetected Continue totalDisplacementForPan:" + totalDisplacementForPan);
1586 else if (panGesture.State == Gesture.StateType.Finished || panGesture.State == Gesture.StateType.Cancelled)
1588 PlayOverShootingShadowAnimation();
1589 OnScrollDragEnded();
1590 StopScroll(); // Will replace previous animation so will stop existing one.
1592 if (scrollAnimation == null)
1594 scrollAnimation = new Animation();
1595 scrollAnimation.Finished += ScrollAnimationFinished;
1598 float panVelocity = (ScrollingDirection == Direction.Horizontal) ? panGesture.Velocity.X : panGesture.Velocity.Y;
1602 PageSnap(panVelocity);
1606 if (panVelocity == 0)
1608 float currentScrollPosition = (ScrollingDirection == Direction.Horizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y);
1609 scrollAnimation.DefaultAlphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.Linear);
1610 scrollAnimation.Duration = 0;
1611 scrollAnimation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", currentScrollPosition);
1612 scrollAnimation.Play();
1616 Decelerating(panVelocity, scrollAnimation);
1620 totalDisplacementForPan = 0;
1622 readyToNotice = true;
1623 OnScrollAnimationStarted();
1628 internal void BaseRemove(View view)
1633 internal override bool OnAccessibilityPan(PanGesture gestures)
1635 if (SnapToPage && scrollAnimation != null && scrollAnimation.State == Animation.States.Playing)
1640 OnPanGesture(gestures);
1644 private float CustomScrollAlphaFunction(float progress)
1646 if (panAnimationDelta == 0)
1652 // Parameter "progress" is normalized value. We need to multiply target duration to calculate distance.
1653 // Can get real distance using equation of deceleration (check Decelerating function)
1654 // After get real distance, normalize it
1655 float realDuration = progress * panAnimationDuration;
1656 float realDistance = velocityOfLastPan * ((float)Math.Pow(decelerationRate, realDuration) - 1) / logValueOfDeceleration;
1657 float result = Math.Min(realDistance / Math.Abs(panAnimationDelta), 1.0f);
1663 /// you can override it to custom your decelerating
1665 /// <param name="velocity">Velocity of current pan.</param>
1666 /// <param name="animation">Scroll animation.</param>
1667 [EditorBrowsable(EditorBrowsableState.Never)]
1668 protected virtual void Decelerating(float velocity, Animation animation)
1670 // Decelerating using deceleration equation ===========
1672 // V : velocity (pixel per millisecond)
1673 // V0 : initial velocity
1674 // d : deceleration rate,
1676 // X : final position after decelerating
1677 // log : natural logarithm
1679 // V(t) = V0 * d pow t;
1680 // X(t) = V0 * (d pow t - 1) / log d; <-- Integrate the velocity function
1681 // X(∞) = V0 * d / (1 - d); <-- Result using infinite T can be final position because T is tending to infinity.
1683 // Because of final T is tending to infinity, we should use threshold value to finish.
1684 // Final T = log(-threshold * log d / |V0| ) / log d;
1686 velocityOfLastPan = Math.Abs(velocity);
1688 float currentScrollPosition = -(ScrollingDirection == Direction.Horizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y);
1689 panAnimationDelta = (velocityOfLastPan * decelerationRate) / (1 - decelerationRate);
1690 panAnimationDelta = velocity > 0 ? -panAnimationDelta : panAnimationDelta;
1692 float destination = -(panAnimationDelta + currentScrollPosition);
1693 float adjustDestination = AdjustTargetPositionOfScrollAnimation(destination);
1694 float maxPosition = ScrollAvailableArea != null ? ScrollAvailableArea.Y : maxScrollDistance;
1695 float minPosition = ScrollAvailableArea != null ? ScrollAvailableArea.X : 0;
1697 if (destination < -maxPosition || destination > minPosition)
1699 panAnimationDelta = velocity > 0 ? (currentScrollPosition - minPosition) : (maxPosition - currentScrollPosition);
1700 destination = velocity > 0 ? minPosition : -maxPosition;
1702 if (panAnimationDelta == 0)
1704 panAnimationDuration = 0.0f;
1708 panAnimationDuration = (float)Math.Log((panAnimationDelta * logValueOfDeceleration / velocityOfLastPan + 1), decelerationRate);
1711 Debug.WriteLineIf(LayoutDebugScrollableBase, "\n" +
1712 "OverRange======================= \n" +
1713 "[decelerationRate] " + decelerationRate + "\n" +
1714 "[logValueOfDeceleration] " + logValueOfDeceleration + "\n" +
1715 "[Velocity] " + velocityOfLastPan + "\n" +
1716 "[CurrentPosition] " + currentScrollPosition + "\n" +
1717 "[CandidateDelta] " + panAnimationDelta + "\n" +
1718 "[Destination] " + destination + "\n" +
1719 "[Duration] " + panAnimationDuration + "\n" +
1720 "================================ \n"
1725 panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
1727 if (adjustDestination != destination)
1729 destination = adjustDestination;
1730 panAnimationDelta = destination + currentScrollPosition;
1731 velocityOfLastPan = Math.Abs(panAnimationDelta * logValueOfDeceleration / ((float)Math.Pow(decelerationRate, panAnimationDuration) - 1));
1732 panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
1735 Debug.WriteLineIf(LayoutDebugScrollableBase, "\n" +
1736 "================================ \n" +
1737 "[decelerationRate] " + decelerationRate + "\n" +
1738 "[logValueOfDeceleration] " + logValueOfDeceleration + "\n" +
1739 "[Velocity] " + velocityOfLastPan + "\n" +
1740 "[CurrentPosition] " + currentScrollPosition + "\n" +
1741 "[CandidateDelta] " + panAnimationDelta + "\n" +
1742 "[Destination] " + destination + "\n" +
1743 "[Duration] " + panAnimationDuration + "\n" +
1744 "================================ \n"
1748 finalTargetPosition = destination;
1750 customScrollAlphaFunction = new UserAlphaFunctionDelegate(CustomScrollAlphaFunction);
1751 animation.DefaultAlphaFunction = new AlphaFunction(customScrollAlphaFunction);
1752 GC.KeepAlive(customScrollAlphaFunction);
1753 animation.Duration = (int)panAnimationDuration;
1754 animation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", destination);
1758 private void ScrollAnimationFinished(object sender, EventArgs e)
1760 OnScrollAnimationEnded();
1764 /// Adjust scrolling position by own scrolling rules.
1765 /// Override this function when developer wants to change destination of flicking.(e.g. always snap to center of item)
1767 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
1768 [EditorBrowsable(EditorBrowsableState.Never)]
1769 protected virtual float AdjustTargetPositionOfScrollAnimation(float position)
1775 /// Scroll position given to ScrollTo.
1776 /// This is the position in the opposite direction to the position of ContentContainer.
1778 /// <since_tizen> 8 </since_tizen>
1779 public Position ScrollPosition
1783 return new Position(-ContentContainer.Position);
1788 /// Current scroll position in the middle of ScrollTo animation.
1789 /// This is the position in the opposite direction to the current position of ContentContainer.
1791 /// <since_tizen> 8 </since_tizen>
1792 public Position ScrollCurrentPosition
1796 return new Position(-ContentContainer.CurrentPosition);
1801 /// Remove all children in ContentContainer.
1803 /// <param name="dispose">If true, removed child is disposed.</param>
1804 [EditorBrowsable(EditorBrowsableState.Never)]
1805 public void RemoveAllChildren(bool dispose = false)
1807 RecursiveRemoveChildren(ContentContainer, dispose);
1810 private void RecursiveRemoveChildren(View parent, bool dispose)
1816 int maxChild = (int)parent.GetChildCount();
1817 for (int i = maxChild - 1; i >= 0; --i)
1819 View child = parent.GetChildAt((uint)i);
1824 RecursiveRemoveChildren(child, dispose);
1825 parent.Remove(child);
1834 [EditorBrowsable(EditorBrowsableState.Never)]
1835 public override View GetNextFocusableView(View currentFocusedView, View.FocusDirection direction, bool loopEnabled)
1837 if (currentFocusedView == this)
1842 View nextFocusedView = FocusManager.Instance.GetNearestFocusableActor(this, currentFocusedView, direction);
1844 if (nextFocusedView != null)
1846 View view = nextFocusedView;
1847 while (view.GetParent() is View && view.GetParent() != ContentContainer)
1849 view = (View)view.GetParent();
1851 if (view.GetParent() == ContentContainer)
1853 // Check next focused view is inside of visible area.
1854 // If it is not, move scroll position to make it visible.
1855 float left = nextFocusedView.ScreenPosition.X;
1856 float right = nextFocusedView.ScreenPosition.X + nextFocusedView.Size.Width;
1857 float top = nextFocusedView.ScreenPosition.Y;
1858 float bottom = nextFocusedView.ScreenPosition.Y + nextFocusedView.Size.Height;
1860 float visibleRectangleLeft = ScreenPosition.X;
1861 float visibleRectangleRight = ScreenPosition.X + Size.Width;
1862 float visibleRectangleTop = ScreenPosition.Y;
1863 float visibleRectangleBottom = ScreenPosition.Y + Size.Height;
1865 if (ScrollingDirection == Direction.Horizontal)
1867 if (left < visibleRectangleLeft)
1869 ScrollTo(left- ContentContainer.ScreenPosition.X, true);
1871 else if (right > visibleRectangleRight)
1873 ScrollTo(right - Size.Width - ContentContainer.ScreenPosition.X, true);
1878 if (top < visibleRectangleTop)
1880 ScrollTo(top - ContentContainer.ScreenPosition.Y, true);
1882 else if (bottom > visibleRectangleBottom)
1884 ScrollTo(bottom - Size.Height - ContentContainer.ScreenPosition.Y, true);
1889 return nextFocusedView;
1893 [EditorBrowsable(EditorBrowsableState.Never)]
1894 protected override bool AccessibilityScrollToChild(View child)
1901 if (ScrollingDirection == Direction.Horizontal)
1903 if (child.ScreenPosition.X + child.Size.Width <= this.ScreenPosition.X)
1907 PageSnap(PageFlickThreshold + 1);
1911 ScrollTo((float)(child.ScreenPosition.X - ContentContainer.ScreenPosition.X), false);
1914 else if (child.ScreenPosition.X >= this.ScreenPosition.X + this.Size.Width)
1918 PageSnap(-(PageFlickThreshold + 1));
1922 ScrollTo((float)(child.ScreenPosition.X + child.Size.Width - ContentContainer.ScreenPosition.X - this.Size.Width), false);
1928 if (child.ScreenPosition.Y + child.Size.Height <= this.ScreenPosition.Y)
1932 PageSnap(PageFlickThreshold + 1);
1936 ScrollTo((float)(child.ScreenPosition.Y - ContentContainer.ScreenPosition.Y), false);
1939 else if (child.ScreenPosition.Y >= this.ScreenPosition.Y + this.Size.Height)
1943 PageSnap(-(PageFlickThreshold + 1));
1947 ScrollTo((float)(child.ScreenPosition.Y + child.Size.Height - ContentContainer.ScreenPosition.Y - this.Size.Height), false);