表单:ListView不回收单元格
我正在使用ListView显示自定义ViewCell的长列表。我使用ListViewCachingStrategy.RecycleElement只加载可见单元格,并在它们离开屏幕时进行回收。它不起作用了 自定义viewcell的构造函数中的断点显示它被调用的次数与ListView的ItemSource中的项相同,因此我知道它正在为每个项实例化一个单元格,而不仅仅是可见项。那是不对的。此外,如果我的手机内存足够大,那么应用程序就会崩溃,因为它无法为所有手机分配足够的内存 这是我的列表视图表单:ListView不回收单元格,listview,xamarin.forms,out-of-memory,Listview,Xamarin.forms,Out Of Memory,我正在使用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 Emulator上,我得到一个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;
}
}
当我根据您的代码组合一个样本时,有一千个项目,我只创建了六个单元格,除非
menuItemGridHeight
(RowHeight
)太小,在这种情况下,我会实例化一千个单元格
您可以检查menuItemGridHeight
?我会考虑取消设置<代码> RowHeight < /Cord>属性。
值为0或1表示您的行为。。。100不代表。。。不确定截止点在哪里,但我假设在决定是否可以重复使用单元格时,它会查看现有单元格是否适合要呈现的新项目的内容。行高为100个单位。删除设置行高度的行确实会使一切正常工作(非常奇怪),但现在我遇到了一个新问题,即我的行没有正确的高度。给自定义单元格的网格一个高度请求似乎也不能减少它,所以我必须找到另一种方法。好的,我现在已经让它工作了。要使行具有适当的高度,而不会导致listview不回收单元格的奇怪行为,我所做的是设置listview.HasUnlocateRows=true,然后在自定义viewcell的构造函数中,将继承的height属性设置为所需的高度。我仍然不知道为什么将ListView.RowHeight设置为100这样的数字会破坏单元格循环。