Android - 滚动时Listview变得混乱。与ListView回收相关

时间:2013-12-10 21:45:35

标签: android listview android-listview listviewitem

我有一个列表视图,根据某些条件显示两个名称。有时会显示单独的名称,有时第一个名称和第二个名称将显示在列表视图的视图(每行)中。最初列表出现时一切正常。但是当我滚动列表时,问题就出现了。

第0行在列表视图中变得混乱。它显示了第二个名称,虽然我已将其编程为不可见。当我向下滚动并返回时,其他行也会发生同样的情况。

我知道这是由于列表回收。但我已经实现了提到的代码以避免这种情况。但这仍然在发生。你能帮助我克服这个问题。

下面是代码段。谢谢你的时间。

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    View view = convertView;
    ViewHolder holder;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(row, null);

        holder = new ViewHolder();
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    if ((items == null) || ((position + 1) > items.size()))
        return view;

    objBean = items.get(position);

    holder.firstcontactname = (TextView) view.findViewById(R.id.firstcontactname);
    holder.secondcontactname = (TextView) view.findViewById(R.id.secondcontactname);

    }


if (holder.firstcontactname != null && null != objBean.getfirstcontactname()
            && objBean.getfirstcontactname().trim().length() > 0) {
        //holder.firstcontactname.setText(Html.fromHtml("" + "<b>"+"<font color='black'>"+objBean.getfirstcontactname()));
        holder.firstcontactname.setText(Html.fromHtml("" + "<b>"+objBean.getfirstcontactname()));
    }

    if (holder.secondcontactname != null && null != objBean.getsecondcontactname()
            && objBean.getsecondcontactname().trim().length() > 0) {
        //holder.secondcontactname.setText(Html.fromHtml("" + "<b>"+"<font color='black'>"+objBean.getsecondcontactname()));
        holder.secondcontactname.setText(Html.fromHtml("" + "<b>"+objBean.getsecondcontactname()));
    }

    if (objBean.getsecondcontactname()==null ) {
        holder.secondcontactname.setVisibility(View.INVISIBLE);
    } 


return view;
    }

2 个答案:

答案 0 :(得分:1)

首先,你应该找到TextViews

holder.firstcontactname = (TextView) view.findViewById(R.id.firstcontactname);

在实例化新Holder()之后,在if(view == null)块内部。

其次,由于视图回收,您需要处理每个“其他”案例。现在你正在检查holder.firstcontactname是否为null然后设置文本,如果它为空('else'的情况)你需要将文本设置为空或隐藏文本字段,否则文本将仍然存在在前一行中膨胀的旧视图。

答案 1 :(得分:1)

这不是你的问题,而是使用这一行:

 if ((items == null) || ((position + 1) > items.size()))
    return view;

覆盖此方法

@Override public int getCount() { return items.size(); }

现在如果项目列表中有内容,则只会调用getview。

现在针对您的问题的答案我想说如果您想要一个简单的解决方案: 每个项目都膨胀一个新视图,不要检查(view == null),你也可以删除持有者模式。把事情简单化。 我知道这不是一种有效的方法,但如果您的列表项目视图很简单并且滚动它的罚款,那么只使用它。否则你需要做一些工作才能让它顺利进行。如果这不适合你,请告诉我。

相关问题