【发布时间】:2011-10-13 13:47:06
【问题描述】:
我为我的列表视图创建了一个自定义适配器,它可以扩展自定义视图,并允许用户过滤列表。
这一切都很好,但问题是我放置在列表视图项中的图标没有跟随过滤后的数据。
示例
请注意图标没有改变位置,但名称已正确过滤。
这是完成自定义列表视图的自定义适配器
我使用的是 Mono,所以它是用 C# 编写的,但希望你们这些 java 人也能知道我在这里做什么......
/// <summary>
/// ArrayAdapter to handle displaying student with risk indicator
/// </summary>
private class StudentListAdapter : ArrayAdapter<Student>
{
private IList<Student> items;
private Context outer_context;
public StudentListAdapter(Context context, int resource, int textViewResourceId, IList<Student> items)
: base(context, resource, textViewResourceId, items)
{
this.items = items;
this.outer_context = context;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
LayoutInflater vi = (LayoutInflater)outer_context.GetSystemService(Context.LayoutInflaterService);
View tmpView = vi.Inflate(Resource.Layout.ItemStudent, null);
// call base.GetView that uses Object.ToString() to keep sorting intact
View v = base.GetView(position, tmpView, parent);
Student s = items[position];
if (s != null)
{
// determine correct risk image
ImageView listRisk = v.FindViewById<ImageView>(Resource.Id.listRisk);
if (s.R != null)
{
switch ((int)s.R.Value)
{
case 1:
listRisk.SetImageResource(Resource.Drawable.risk_green);
break;
case 0:
listRisk.SetImageResource(Resource.Drawable.risk_yellow);
break;
case -1:
listRisk.SetImageResource(Resource.Drawable.risk_red);
break;
case -2:
listRisk.SetImageResource(Resource.Drawable.risk_red2);
break;
default:
listRisk.SetImageResource(Resource.Drawable.risk_gray);
break;
}
}
else
{
listRisk.SetImageResource(Resource.Drawable.risk_gray);
}
}
return v;
}
}
更新
经过一些断点和检查,我发现当列表过滤时,它会在过滤之前重建整个列表
例如,当在过滤字段中键入一个字母时,第一个运行 GetView() 过程的学生 (s) 是 Heath, Ackerson,它是列表中的第一个学生,即使过滤器没有匹配他。
所以,似乎过滤是在运行 GetView 之后进行的,将图像留在原处......仍然不知道如何修复它......
* 完整解决方案 *
http://jondavidjohn.com/blog/2011/08/android-custom-listview-filtering
【问题讨论】:
-
如果您在过滤时放置一些断点,代码是否会碰到代码的 SetImageResource 部分?
-
嗯...不,好电话,我想它不会重新调用 getView
-
基于此,我会检查's'是否是你的罪魁祸首。也许那些学生不在“项目”列表中?
-
@Brian 在帖子末尾更新了新发现
标签: c# android filter mono android-listview