Listview getItemAt返回null
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Listview getItemAt返回null相关的知识,希望对你有一定的参考价值。
我正在尝试移动物品以使用listview
在largeImage style.
内重新排序。问题存在于getItemAt(x, y)
内部的dragdrop
方法中,因为只有当dragDrop
没有完全在现有项目上执行时,此方法才会返回null(通常我在两个项目之间删除,它更直观imo)。
private void lvPictures_DragDrop(object sender, DragEventArgs e)
{
Point p = lvPictures.PointToClient(new Point(e.X, e.Y));
ListViewItem MovetoNewPosition = lvPictures.GetItemAt(p.X, p.Y);
//MovetoNewPosition is null
}
所以重点是,如果在两个项目之间执行dragDrop
,那么如何获得最接近的项目 - 而不是超过一个?
答案向我指出了正确的方向,这就是我如何实现“找到最近”的方法:(可能不完美,但它现在有效)
ListViewItem itemToBeMoved = (e.Data.GetData(typeof(ListView.SelectedListViewItemCollection)) as ListView.SelectedListViewItemCollection)[0];
ListViewItem itemToBeMovedClone = (ListViewItem)itemToBeMoved.Clone();
ListViewItem itemInDropPosition = listView.GetItemAt(p.X, p.Y);
if (itemInDropPosition == null)
{
ListViewItem leftItem = listView.FindNearestItem(SearchDirectionHint.Left, p);
ListViewItem rightItem = listView.FindNearestItem(SearchDirectionHint.Right, p);
if (leftItem == null && rightItem == null)
{
return;
}
else if (leftItem == null)
{
itemInDropPosition = rightItem;
}
else if (rightItem == null)
{
itemInDropPosition = leftItem;
}
else
{
//PGM: appens that if you move to the right or to the left, between two items, the left item (if moving to the right) or the right item (if moving to the left) is wrong, because it select not the first one, but the second
if (rightItem.Index - leftItem.Index > 1 && leftItem.Index < itemToBeMoved.Index && rightItem.Index <= itemToBeMoved.Index)
{
//we are moving to the left
rightItem = listView.Items[rightItem.Index - 1];
}
else if (rightItem.Index - leftItem.Index > 1 && leftItem.Index >= itemToBeMoved.Index && rightItem.Index > itemToBeMoved.Index)
{
//we are moving to the right
leftItem = listView.Items[leftItem.Index + 1];
}
else if (rightItem.Index - leftItem.Index > 1)
{
//significa che è stato spostato sul posto e non va mosso
return;
}
if (Math.Abs(p.X - leftItem.Position.X) < Math.Abs(p.X - rightItem.Position.X))
{
itemInDropPosition = leftItem;
}
else
{
itemInDropPosition = rightItem;
}
}
}
答案
ListView.FindNearestItem会更好地完成你想要完成的任务吗?
以上是关于Listview getItemAt返回null的主要内容,如果未能解决你的问题,请参考以下文章
Android 自定义 ListView onClickListener 返回 null
view、adapter、getActivity()、infragment 都是 null
ListView.setAdapter Null Pointer exception 虽然 adapter.getCount 显示所有记录并且 Listview 也不是 Null [重复]