【发布时间】:2018-01-10 14:39:45
【问题描述】:
我正在使用 ListView 来显示一长串自定义 ViewCell。我正在使用 ListViewCachingStrategy.RecycleElement 以便仅加载可见单元格并在它们离开屏幕时回收它们。它不工作。
我的自定义 viewcell 的构造函数中的断点显示它被调用的次数与 ListView 的 ItemSource 中的项目一样多,因此我知道它为每个项目实例化一个单元格,而不仅仅是可见的项目。那是不对的。此外,如果我的单元格的内存足够大,那么应用程序就会崩溃,因为它无法为所有单元格分配足够的内存。
这是我的列表视图
menuContainer.Content = new ListView(ListViewCachingStrategy.RecycleElement)
{
ItemsSource = menuItems, // about 800 objects
ItemTemplate = new DataTemplate(typeof(CustomCell)),
RowHeight = (int)menuItemGridHeight
};
这是我的自定义 ViewCell,只是一个带有按钮的网格
class CustomCell : ViewCell
{
public CustomCell()
{
Button button = new Button
{
BorderRadius = 0,
BackgroundColor = Color.Transparent
};
Grid grid = new Grid
{
ColumnSpacing = 0,
BackgroundColor = Color.FromRgba(255, 255, 255, 0.8),
ColumnDefinitions = new ColumnDefinitionCollection
{
new ColumnDefinition { Width = new GridLength(15, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength(100, GridUnitType.Star) }
}
};
grid.Children.Add(button, 1, 0);
View = grid;
}
}
在 Android 模拟器上,我收到 Java.Lang.OutOfMemoryError。 iOS 似乎有足够的备用内存不会崩溃。我还验证了应用程序可以正常加载 ItemSource 中的所有对象,所以我知道问题是为所有单元格对象分配内存,而不是 ItemSource 对象。
为什么我的 ListView 不回收它的 ViewCells?
编辑:这是有效的代码。单元格按应有的方式回收,并保持适当的高度。
列表视图...
ListView(ListViewCachingStrategy.RecycleElement)
{
ItemsSource = menuItems, // about 800 objects
ItemTemplate = new DataTemplate(typeof(CustomCell)),
HasUnevenRows = true
};
还有自定义视图单元格...
class CustomCell : ViewCell
{
public CustomCell()
{
Height = 100;
Button button = new Button
{
BorderRadius = 0,
BackgroundColor = Color.Transparent
};
Grid grid = new Grid
{
ColumnSpacing = 0,
BackgroundColor = Color.FromRgba(255, 255, 255, 0.8),
ColumnDefinitions = new ColumnDefinitionCollection
{
new ColumnDefinition { Width = new GridLength(15, GridUnitType.Star) },
new ColumnDefinition { Width = new GridLength(100, GridUnitType.Star) }
}
};
grid.Children.Add(button, 1, 0);
View = grid;
}
}
【问题讨论】:
标签: listview xamarin.forms out-of-memory