android - 失控的ListView

标签 android listview scroll listviewitem listactivity

我在使用 ListActivity 时遇到问题。我扩展了 ArrayAdapter 和 Overridden getView 以填充每一行的数据。我将适配器的 ArrayList 中的一些数据放入 TextView。

我的问题是,当我滚动时,每行的 TextView 填充的文本不在 ArrayList 中相应的数据中。我的意思是:假设我的列表顶部有一行,其中包含填充有空字符串的 TextView。如果我在列表的底部看到一行 TextView 填充了“bob”,然后我轻弹滚动到顶部,则顶部的行现在可能在其 TextView 中有“bob”,但数据位于我的 ArrayList 的那个索引不包含“bob”。它包含空字符串(实际上为空)。如果我继续上下滚动,其他行将填充(或删除)与适配器的 ArrayList 中的内容不对应的数据。

要实现这一点,我不需要快速滚动 ListView。但是,我滚动得越快,困惑的行就越多。

这是我的代码。我意识到每次调用 getView 时我都在使用 findViewById,但这不是重点。我反对 convertView;所以它应该在每一行上抓取正确的 TextView,是吗?

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

    // get the View for this list item
    View v = convertView;
    if (v == null) {
        LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.layout_mylistlist_item, null);
    }

    // get the next object
    MyListItem myItem = m_items.get(position);

    // set up the list item
    if (myItem != null) {
        TextView txtName = (TextView) v.findViewById(R.id.mylist_name);

        // set text
        if (txtName != null && myItem.getName() != null) {
            txtName.setText(myItem.getName());
        }
    }

   // return the created view
    return v;
}

最佳答案

我认为问题出在底部的 if(myItem != null) 检查上。

尝试向该 block 添加一个 else 语句,将 TextView 设置为空字符串。

像这样:

// set up the list item 
TextView txtName = (TextView) v.findViewById(R.id.mylist_name); 
if (myItem != null) {  
    // set text 
    if (txtName != null && myItem.getName() != null) { 
        txtName.setText(myItem.getName()); 
    } else
    {
        txtName.setText("");
    }
} 
else
{
    txtName.setText("");
}

convertview 在传递给您时仍将包含旧数据。即使您的数据无效,您也需要有意覆盖它,否则它会保留其旧数据。

关于android - 失控的ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3513608/

相关文章:

android - 三星 s3 在捕获图像后不会将图像数据返回到 URI,而在所有其他设备上,它工作正常

android - 将 SVG 图像解码为位图

android - 我如何在 ListView 中膨胀三个布局?

android - 滚动或添加 ListView 中的项目时按钮文本消失,Android

javascript - iscroll - 在 jsfiddle 中不起作用

javascript - 如果内容大于屏幕高度,弹出窗口始终显示为固定在顶部边缘但会随着整个页面滚动?

android - sendKeys - 发送特殊字符

java - 如何修复在改造 Android 中发送多部分文件时出现服务器错误 500

jquery - 在列表之间放置空格

android - 获取android ListView中选中项的数量