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
/
ViewPool.cs
79 lines (62 loc) · 1.49 KB
/
ViewPool.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
using System;
using System.Collections.Generic;
using Android.Views;
using AView = Android.Views.View;
namespace Xamarin.Forms.Platform.Android
{
public class ViewPool : IDisposable
{
readonly Dictionary<Type, Stack<AView>> _freeViews = new Dictionary<Type, Stack<AView>>();
readonly ViewGroup _viewGroup;
bool _disposed;
public ViewPool(ViewGroup viewGroup)
{
_viewGroup = viewGroup;
}
public void Dispose()
{
if (_disposed)
return;
foreach (Stack<AView> views in _freeViews.Values)
{
foreach (AView view in views)
view.Dispose();
}
_disposed = true;
}
public void ClearChildren()
{
if (_disposed)
throw new ObjectDisposedException(null);
ClearChildren(_viewGroup);
}
public TView GetFreeView<TView>() where TView : AView
{
if (_disposed)
throw new ObjectDisposedException(null);
Stack<AView> views;
if (_freeViews.TryGetValue(typeof(TView), out views) && views.Count > 0)
return (TView)views.Pop();
return null;
}
void ClearChildren(ViewGroup group)
{
if (group == null)
return;
int count = group.ChildCount;
for (var i = 0; i < count; i++)
{
AView child = group.GetChildAt(i);
var g = child as ViewGroup;
if (g != null)
ClearChildren(g);
Type childType = child.GetType();
Stack<AView> stack;
if (!_freeViews.TryGetValue(childType, out stack))
_freeViews[childType] = stack = new Stack<AView>();
stack.Push(child);
}
group.RemoveAllViews();
}
}
}