ListView适配器,防止更新

时间:2012-10-08 11:14:13

标签: android listview simpleadapter

我已经为项目的日期分组扩展了SimpleAdapter,这在项目创建时正常运行。列表项包含分组视图,如果项目属于当前日期组,我的适配器将隐藏此视图:

TextView Title (2012-10-08) - visible
TextView Name  (Foo)        - visible

TextView Title (2012-10-08) - hidden
TextView Name  (Bar)        - visible

TextView Title (2012-10-07) - visible
TextView Name  (Baz)        - visible

TextView Title (2012-10-07) - hidden
TextView Name  (Etc)        - visible

现在,如果我在完全填充列表中的第二个项目下方向下滚动,则再次向上滚动时隐藏视图将变为可见。为什么会发生这种情况?如何防止它?

我不会在onCreate之后更改适配器,因此我不知道为什么我的ListViewAdapter会更改查看状态。

DateAdapter:

public class DateAdapter extends SimpleAdapter
{
    protected   ArrayList<HashMap<String, String>>  items;
    private     String                  prevDate = "";
    private     SimpleDateFormat            dateFormat = new SimpleDateFormat("EEEE, dd/MM yyyy", Locale.getDefault());

    public DateAdapter (Context context, ArrayList<HashMap<String, String>> items, int resource, String[] from, int[] to)
    {
        super(context, items, resource, from, to);
        this.items = items;
    }

    @Override
    public View getView (int position, View convertView, ViewGroup parent)
    {
        View view = super.getView(position, convertView, parent);

        try
        {
            HashMap<String, String> item = this.items.get(position);
            Long itemTime = Long.parseLong(item.get("timedate")) * 1000;

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(itemTime);
            String dateString = dateFormat.format(calendar.getTime());

            TextView section = (TextView) view.findViewById(R.id.sectionTitle);

            if (!dateString.equals(this.prevDate))
            {
                this.prevDate = dateString;
                section.setText(dateFormat.format(calendar.getTime()));
                section.setVisibility(View.VISIBLE);
            }
        }
        catch (Exception e) { Debug.e(e); }

        return view;
    }
}

1 个答案:

答案 0 :(得分:1)

View view = super.getView(position,convertView,parent);

此行返回新创建的视图,仅当提供的convertView为null时,如果convertView不为null,则返回相同的视图。因此,当它返回相同的convertView实例时,可能会看到具有可见性的视图可见。所以,你要做的就是填补这个条件的其他条件

    if (!dateString.equals(this.prevDate)){} 

您将视图可见性设置为INVISIBLE。告诉我它有用吗?