我在使用 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/