This repository has been archived by the owner on May 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathListViewRenderer.cs
731 lines (613 loc) · 19.5 KB
/
ListViewRenderer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
using System.ComponentModel;
using Android.Content;
#if __ANDROID_29__
using AndroidX.Core.Widget;
using AndroidX.SwipeRefreshLayout.Widget;
#else
using Android.Support.V4.Widget;
#endif
using Android.Views;
using AListView = Android.Widget.ListView;
using AView = Android.Views.View;
using Xamarin.Forms.Internals;
using System;
using Xamarin.Forms.PlatformConfiguration.AndroidSpecific;
using Android.Widget;
using Android.Runtime;
namespace Xamarin.Forms.Platform.Android
{
public class ListViewRenderer : ViewRenderer<ListView, AListView>, SwipeRefreshLayout.IOnRefreshListener
{
ListViewAdapter _adapter;
bool _disposed;
IVisualElementRenderer _headerRenderer;
IVisualElementRenderer _footerRenderer;
Container _headerView;
Container _footerView;
bool _isAttached;
ScrollToRequestedEventArgs _pendingScrollTo;
SwipeRefreshLayout _refresh;
IListViewController Controller => Element;
ITemplatedItemsView<Cell> TemplatedItemsView => Element;
ScrollBarVisibility _defaultHorizontalScrollVisibility = 0;
ScrollBarVisibility _defaultVerticalScrollVisibility = 0;
public ListViewRenderer(Context context) : base(context)
{
AutoPackage = false;
}
[Obsolete("This constructor is obsolete as of version 2.5. Please use ListViewRenderer(Context) instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public ListViewRenderer()
{
AutoPackage = false;
}
void SwipeRefreshLayout.IOnRefreshListener.OnRefresh()
{
IListViewController controller = Element;
controller.SendRefreshing();
}
protected override void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
if (disposing)
{
Controller.ScrollToRequested -= OnScrollToRequested;
if (_headerRenderer != null)
{
Platform.ClearRenderer(_headerRenderer.View);
_headerRenderer.Dispose();
_headerRenderer = null;
}
_headerView?.Dispose();
_headerView = null;
if (_footerRenderer != null)
{
Platform.ClearRenderer(_footerRenderer.View);
_footerRenderer.Dispose();
_footerRenderer = null;
}
_footerView?.Dispose();
_footerView = null;
if (Control != null)
{
// Unhook the adapter from the ListView before disposing of it
Control.Adapter = null;
Control.SetOnScrollListener(null);
}
if (_adapter != null)
{
_adapter.Dispose();
_adapter = null;
}
}
base.Dispose(disposing);
}
protected override Size MinimumSize()
{
return new Size(40, 40);
}
protected virtual SwipeRefreshLayout CreateNativePullToRefresh(Context context)
=> new SwipeRefreshLayoutWithFixedNestedScrolling(context);
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
if (Forms.IsLollipopOrNewer && Control != null)
Control.NestedScrollingEnabled = (Parent.GetParentOfType<NestedScrollView>() != null);
_isAttached = true;
_adapter.IsAttachedToWindow = _isAttached;
UpdateIsRefreshing(isInitialValue: true);
}
protected override void OnDetachedFromWindow()
{
base.OnDetachedFromWindow();
_isAttached = false;
_adapter.IsAttachedToWindow = _isAttached;
}
protected override AListView CreateNativeControl()
{
return new AListView(Context);
}
protected override void OnElementChanged(ElementChangedEventArgs<ListView> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
((IListViewController)e.OldElement).ScrollToRequested -= OnScrollToRequested;
if (Control != null)
{
// Unhook the adapter from the ListView before disposing of it
Control.Adapter = null;
Control.SetOnScrollListener(null);
}
if (_adapter != null)
{
_adapter.Dispose();
_adapter = null;
}
}
if (e.NewElement != null)
{
AListView nativeListView = Control;
if (nativeListView == null)
{
var ctx = Context;
nativeListView = CreateNativeControl();
_refresh = CreateNativePullToRefresh(ctx);
_refresh.SetOnRefreshListener(this);
_refresh.AddView(nativeListView, new LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent));
SetNativeControl(nativeListView, _refresh);
_headerView = new Container(ctx);
nativeListView.AddHeaderView(_headerView, null, false);
_footerView = new Container(ctx);
nativeListView.AddFooterView(_footerView, null, false);
}
((IListViewController)e.NewElement).ScrollToRequested += OnScrollToRequested;
Control?.SetOnScrollListener(new ListViewScrollDetector(this));
nativeListView.DividerHeight = 0;
nativeListView.Focusable = false;
nativeListView.DescendantFocusability = DescendantFocusability.AfterDescendants;
nativeListView.OnFocusChangeListener = this;
nativeListView.Adapter = _adapter = e.NewElement.IsGroupingEnabled && e.NewElement.OnThisPlatform().IsFastScrollEnabled() ? new GroupedListViewAdapter(Context, nativeListView, e.NewElement) : new ListViewAdapter(Context, nativeListView, e.NewElement);
_adapter.HeaderView = _headerView;
_adapter.FooterView = _footerView;
_adapter.IsAttachedToWindow = _isAttached;
UpdateHeader();
UpdateFooter();
UpdateIsSwipeToRefreshEnabled();
UpdateFastScrollEnabled();
UpdateSelectionMode();
UpdateSpinnerColor();
UpdateHorizontalScrollBarVisibility();
UpdateVerticalScrollBarVisibility();
}
}
internal void ClickOn(AView viewCell)
{
if (Control == null)
{
return;
}
var position = Control.GetPositionForView(viewCell);
var id = Control.GetItemIdAtPosition(position);
viewCell.PerformHapticFeedback(FeedbackConstants.ContextClick);
_adapter.OnItemClick(Control, viewCell, position, id);
}
internal void LongClickOn(AView viewCell)
{
if (Control == null)
{
return;
}
var position = Control.GetPositionForView(viewCell);
var id = Control.GetItemIdAtPosition(position);
viewCell.PerformHapticFeedback(FeedbackConstants.ContextClick);
_adapter.OnItemLongClick(Control, viewCell, position, id);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == "HeaderElement")
UpdateHeader();
else if (e.PropertyName == "FooterElement")
UpdateFooter();
else if (e.PropertyName == "RefreshAllowed")
UpdateIsSwipeToRefreshEnabled();
else if (e.PropertyName == ListView.IsPullToRefreshEnabledProperty.PropertyName)
UpdateIsSwipeToRefreshEnabled();
else if (e.PropertyName == ListView.IsRefreshingProperty.PropertyName)
UpdateIsRefreshing();
else if (e.PropertyName == ListView.SeparatorColorProperty.PropertyName || e.PropertyName == ListView.SeparatorVisibilityProperty.PropertyName)
_adapter.NotifyDataSetChanged();
else if (e.PropertyName == PlatformConfiguration.AndroidSpecific.ListView.IsFastScrollEnabledProperty.PropertyName)
UpdateFastScrollEnabled();
else if (e.PropertyName == ListView.SelectionModeProperty.PropertyName)
UpdateSelectionMode();
else if (e.PropertyName == ListView.RefreshControlColorProperty.PropertyName)
UpdateSpinnerColor();
else if (e.PropertyName == ScrollView.HorizontalScrollBarVisibilityProperty.PropertyName)
UpdateHorizontalScrollBarVisibility();
else if (e.PropertyName == ScrollView.VerticalScrollBarVisibilityProperty.PropertyName)
UpdateVerticalScrollBarVisibility();
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
if (_pendingScrollTo != null)
{
OnScrollToRequested(this, _pendingScrollTo);
_pendingScrollTo = null;
}
}
void OnScrollToRequested(object sender, ScrollToRequestedEventArgs e)
{
if (!_isAttached)
{
_pendingScrollTo = e;
return;
}
Cell cell;
int position;
var scrollArgs = (ITemplatedItemsListScrollToRequestedEventArgs)e;
var templatedItems = TemplatedItemsView.TemplatedItems;
if (Element.IsGroupingEnabled)
{
var results = templatedItems.GetGroupAndIndexOfItem(scrollArgs.Group, scrollArgs.Item);
if (results.Item1 == -1 || results.Item2 == -1)
return;
var group = templatedItems.GetGroup(results.Item1);
cell = group[results.Item2];
position = templatedItems.GetGlobalIndexForGroup(group) + results.Item2 + 1;
}
else
{
position = templatedItems.GetGlobalIndexOfItem(scrollArgs.Item);
if (position == -1)
return;
cell = templatedItems[position];
}
//Android offsets position of cells when using header
int realPositionWithHeader = position + 1;
if (e.Position == ScrollToPosition.MakeVisible)
{
if (e.ShouldAnimate)
Control.SmoothScrollToPosition(realPositionWithHeader);
else
Control.SetSelection(realPositionWithHeader);
return;
}
int height = Control.Height;
var cellHeight = (int)cell.RenderHeight;
if (cellHeight == -1)
{
int first = Control.FirstVisiblePosition;
if (first <= position && position <= Control.LastVisiblePosition)
cellHeight = Control.GetChildAt(position - first).Height;
else
{
AView view = _adapter.GetView(position, null, null);
view.Measure(MeasureSpecFactory.MakeMeasureSpec(Control.Width, MeasureSpecMode.AtMost), MeasureSpecFactory.MakeMeasureSpec(0, MeasureSpecMode.Unspecified));
cellHeight = view.MeasuredHeight;
}
}
var y = 0;
if (e.Position == ScrollToPosition.Center)
y = height / 2 - cellHeight / 2;
else if (e.Position == ScrollToPosition.End)
y = height - cellHeight;
if (e.ShouldAnimate)
Control.SmoothScrollToPositionFromTop(realPositionWithHeader, y);
else
Control.SetSelectionFromTop(realPositionWithHeader, y);
}
void UpdateFooter()
{
var footer = (VisualElement)Controller.FooterElement;
if (_footerRenderer != null)
{
var reflectableType = _footerRenderer as System.Reflection.IReflectableType;
var rendererType = reflectableType != null ? reflectableType.GetTypeInfo().AsType() : _footerRenderer.GetType();
if (footer == null || Registrar.Registered.GetHandlerTypeForObject(footer) != rendererType)
{
if (_footerView != null)
_footerView.Child = null;
Platform.ClearRenderer(_footerRenderer.View);
_footerRenderer.Dispose();
_footerRenderer = null;
}
}
if (footer == null)
return;
if (_footerRenderer != null)
_footerRenderer.SetElement(footer);
else
{
_footerRenderer = Platform.CreateRenderer(footer, Context);
if (_footerView != null)
_footerView.Child = _footerRenderer;
}
Platform.SetRenderer(footer, _footerRenderer);
}
void UpdateHeader()
{
var header = (VisualElement)Controller.HeaderElement;
if (_headerRenderer != null)
{
var reflectableType = _headerRenderer as System.Reflection.IReflectableType;
var rendererType = reflectableType != null ? reflectableType.GetTypeInfo().AsType() : _headerRenderer.GetType();
if (header == null || Registrar.Registered.GetHandlerTypeForObject(header) != rendererType)
{
if (_headerView != null)
_headerView.Child = null;
Platform.ClearRenderer(_headerRenderer.View);
_headerRenderer.Dispose();
_headerRenderer = null;
}
}
if (header == null)
return;
if (_headerRenderer != null)
_headerRenderer.SetElement(header);
else
{
_headerRenderer = Platform.CreateRenderer(header, Context);
if (_headerView != null)
_headerView.Child = _headerRenderer;
}
Platform.SetRenderer(header, _headerRenderer);
}
void UpdateIsRefreshing(bool isInitialValue = false)
{
if (_refresh != null)
{
var isRefreshing = Element.IsRefreshing;
if (isRefreshing && isInitialValue)
{
_refresh.Refreshing = false;
_refresh.Post(() =>
{
if(_refresh.IsDisposed())
return;
_refresh.Refreshing = true;
});
}
else
_refresh.Refreshing = isRefreshing;
}
}
void UpdateIsSwipeToRefreshEnabled()
{
if (_refresh != null)
_refresh.Enabled = Element.IsPullToRefreshEnabled && (Element as IListViewController).RefreshAllowed;
}
void UpdateFastScrollEnabled()
{
if (Control != null)
{
Control.FastScrollEnabled = Element.OnThisPlatform().IsFastScrollEnabled();
}
}
void UpdateSelectionMode()
{
if (Control != null)
{
if (Element.SelectionMode == ListViewSelectionMode.None)
{
Control.ChoiceMode = ChoiceMode.None;
Element.SelectedItem = null;
}
else if (Element.SelectionMode == ListViewSelectionMode.Single)
{
Control.ChoiceMode = ChoiceMode.Single;
}
}
}
void UpdateSpinnerColor()
{
if (_refresh != null)
_refresh.SetColorSchemeColors(Element.RefreshControlColor.ToAndroid());
}
void UpdateHorizontalScrollBarVisibility()
{
if (_defaultHorizontalScrollVisibility == 0)
{
_defaultHorizontalScrollVisibility = Control.HorizontalScrollBarEnabled ? ScrollBarVisibility.Always : ScrollBarVisibility.Never;
}
var newHorizontalScrollVisiblility = Element.HorizontalScrollBarVisibility;
if (newHorizontalScrollVisiblility == ScrollBarVisibility.Default)
{
newHorizontalScrollVisiblility = _defaultHorizontalScrollVisibility;
}
Control.HorizontalScrollBarEnabled = newHorizontalScrollVisiblility == ScrollBarVisibility.Always;
}
void UpdateVerticalScrollBarVisibility()
{
if (_defaultVerticalScrollVisibility == 0)
_defaultVerticalScrollVisibility = Control.VerticalScrollBarEnabled ? ScrollBarVisibility.Always : ScrollBarVisibility.Never;
var newVerticalScrollVisibility = Element.VerticalScrollBarVisibility;
if (newVerticalScrollVisibility == ScrollBarVisibility.Default)
newVerticalScrollVisibility = _defaultVerticalScrollVisibility;
Control.VerticalScrollBarEnabled = newVerticalScrollVisibility == ScrollBarVisibility.Always;
}
internal class Container : ViewGroup
{
IVisualElementRenderer _child;
public Container(IntPtr p, global::Android.Runtime.JniHandleOwnership o) : base(p, o)
{
// Added default constructor to prevent crash when accessing header/footer row in ListViewAdapter.Dispose
}
public Container(Context context) : base(context)
{
}
public IVisualElementRenderer Child
{
set
{
if (_child != null)
RemoveView(_child.View);
_child = value;
if (value != null)
AddView(value.View);
}
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
if (_child == null)
return;
_child.UpdateLayout();
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
if (_child?.Element == null)
{
SetMeasuredDimension(0, 0);
return;
}
VisualElement element = _child.Element;
Context ctx = Context;
var width = (int)ctx.FromPixels(MeasureSpecFactory.GetSize(widthMeasureSpec));
SizeRequest request = element.Measure(width, double.PositiveInfinity, MeasureFlags.IncludeMargins);
Xamarin.Forms.Layout.LayoutChildIntoBoundingRegion(element, new Rectangle(0, 0, width, request.Request.Height));
int widthSpec = MeasureSpecFactory.MakeMeasureSpec((int)ctx.ToPixels(width), MeasureSpecMode.Exactly);
int heightSpec = MeasureSpecFactory.MakeMeasureSpec((int)ctx.ToPixels(request.Request.Height), MeasureSpecMode.Exactly);
_child.View.Measure(widthMeasureSpec, heightMeasureSpec);
SetMeasuredDimension(widthSpec, heightSpec);
}
}
class SwipeRefreshLayoutWithFixedNestedScrolling : SwipeRefreshLayout
{
float _touchSlop;
float _initialDownY;
bool _nestedScrollAccepted;
bool _nestedScrollCalled;
public SwipeRefreshLayoutWithFixedNestedScrolling(Context ctx) : base(ctx)
{
_touchSlop = ViewConfiguration.Get(ctx).ScaledTouchSlop;
}
public override bool OnInterceptTouchEvent(MotionEvent ev)
{
if (ev.Action == MotionEventActions.Down)
_initialDownY = ev.GetAxisValue(Axis.Y);
var isBeingDragged = base.OnInterceptTouchEvent(ev);
if (!isBeingDragged && ev.Action == MotionEventActions.Move && _nestedScrollAccepted && !_nestedScrollCalled)
{
var y = ev.GetAxisValue(Axis.Y);
var dy = (y - _initialDownY) / 2;
isBeingDragged = dy > _touchSlop;
}
return isBeingDragged;
}
public override void OnNestedScrollAccepted(AView child, AView target, [GeneratedEnum] ScrollAxis axes)
{
base.OnNestedScrollAccepted(child, target, axes);
_nestedScrollAccepted = true;
_nestedScrollCalled = false;
}
public override void OnStopNestedScroll(AView child)
{
base.OnStopNestedScroll(child);
_nestedScrollAccepted = false;
}
public override void OnNestedScroll(AView target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed)
{
base.OnNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
_nestedScrollCalled = true;
}
}
class ListViewScrollDetector : Java.Lang.Object, AbsListView.IOnScrollListener
{
class TrackElement
{
public TrackElement(int position)
{
_position = position;
}
readonly int _position;
AView _trackedView;
int _trackedViewPrevPosition;
int _trackedViewPrevTop;
public void SyncState(AbsListView view)
{
if (view.ChildCount > 0)
{
_trackedView = GetChild(view);
_trackedViewPrevTop = GetY();
_trackedViewPrevPosition = view.GetPositionForView(_trackedView);
}
}
public void Reset()
{
_trackedView = null;
}
public bool IsSafeToTrack(AbsListView view)
{
return _trackedView != null && _trackedView.Parent == view && view.GetPositionForView(_trackedView) == _trackedViewPrevPosition;
}
public int GetDeltaY()
{
return GetY() - _trackedViewPrevTop;
}
AView GetChild(AbsListView view)
{
switch (_position)
{
case 0:
return view.GetChildAt(0);
case 1:
case 2:
return view.GetChildAt(view.ChildCount / 2);
case 3:
return view.GetChildAt(view.ChildCount - 1);
default:
return null;
}
}
int GetY()
{
return _position <= 1 ? _trackedView.Bottom : _trackedView.Top;
}
}
readonly ListView _element;
readonly float _density;
int _contentOffset;
public ListViewScrollDetector(ListViewRenderer renderer)
{
_element = renderer.Element;
_density = renderer.Context.Resources.DisplayMetrics.Density;
}
void SendScrollEvent(double y)
{
var element = _element;
double offset = Math.Abs(y) / _density;
var args = new ScrolledEventArgs(0, offset);
element?.SendScrolled(args);
}
readonly TrackElement[] _trackElements =
{
new TrackElement(0), // Top view, bottom Y
new TrackElement(1), // Mid view, bottom Y
new TrackElement(2), // Mid view, top Y
new TrackElement(3) // Bottom view, top Y
};
public void OnScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
var wasTracked = false;
foreach (TrackElement t in _trackElements)
{
if (!wasTracked)
{
if (t.IsSafeToTrack(view))
{
wasTracked = true;
_contentOffset += t.GetDeltaY();
SendScrollEvent(_contentOffset);
t.SyncState(view);
}
else
{
t.Reset();
t.SyncState(view);
}
}
else
{
t.SyncState(view);
}
}
}
public void OnScrollStateChanged(AbsListView view, ScrollState scrollState)
{
if (scrollState == ScrollState.TouchScroll || scrollState == ScrollState.Fling)
{
foreach (TrackElement t in _trackElements)
{
t.SyncState(view);
}
}
}
}
}
}