【发布时间】:2020-02-09 02:13:35
【问题描述】:
新手在这里做课程作业。
我正在制作一个 Xamarin C# 应用程序,您可以在其中创建一个对象列表,这些对象显示在 UI 中,目的是跟踪桌面/棋盘游戏中的回合。 为了显示轮到谁,当你点击一个旋转按钮时,轮到他们的对象的 ListView 单元格会改变颜色,而其他的则设置为白色。 如果屏幕太小或屏幕外有任何对象,应用程序在按下旋转按钮时会崩溃。
如何防止这种崩溃?我可以将数据保存在内存中,这样当你向下滚动时,轮到他们的单位会是蓝色的? ListView 能做到这一点吗?
这是按钮的工作原理
Button _rotateButton = FindViewById<Button>(Resource.Id.rotateButton);
int rotatePrevious = -1;
int rotateCurrent = 0;
_rotateButton.Click += delegate
{
int rotateCount = ItemUnits.Count();
if(rotateCount != 0)
{
if (rotateCurrent == 0)
{
_rotateButton.Text = "End Turn";
}
if(rotatePrevious != -1)
{
ItemUnits[rotatePrevious].IsSelected = false;
}
if (rotateCurrent == rotateCount)
{
foreach(ItemUnit iu in ItemUnits)
{
iu.IsSelected = false;
View inactiveView = listView.GetChildAt(ItemUnits.IndexOf(iu));
inactiveView.SetBackgroundResource(Resource.Color.colorPrimary);
}
rotateCurrent = 0;
rotatePrevious = -1;
_rotateButton.Text = "New Round";
}
else
{
ItemUnits[rotateCurrent].IsSelected = true;
foreach (ItemUnit iu in ItemUnits)
{
if (iu.IsSelected == true)
{
View activeView = listView.GetChildAt(ItemUnits.IndexOf(iu));
activeView.SetBackgroundResource(Resource.Color.colorAccent);
}
else
{
View inactiveView = listView.GetChildAt(ItemUnits.IndexOf(iu));
inactiveView.SetBackgroundResource(Resource.Color.colorPrimary);
}
}
rotateCurrent++;
rotatePrevious++;
if (rotateCurrent == rotateCount)
{
_rotateButton.Text = "End Round";
}
}
}
【问题讨论】:
-
导致崩溃的具体行是什么?有什么例外?
-
当它试图更改 BackgroundResrouce 时,它只是一个空引用异常,因为它试图引用不在屏幕上的 ListView 单元格,我认为这意味着它在上下文中不存在。所以我正在寻找解决方法。
标签: c# android listview xamarin