我用这段代码改变覆盖onListItemClick的每一行的背景颜色
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// First time touching the item
if(mLastPosition==-1) {
mLastPosition = position;
} else {
mLocalBG.remove(String.valueOf(mLastId));
v = l.getChildAt(mLastPosition);
v.setBackgroundColor(Color.WHITE);
mLastPosition = position;
}
mLocalBG.add(String.valueOf(id));
/* The issue: v is returning null right here, but only when touch a row that was below the first ones displayed, rows that needed to be scrolled down */
v = l.getChildAt(position);
v.setBackgroundColor(Color.LTGRAY);
}
如上所述,它完美无缺,直到我向下滚动到下一行,之后 View v
每次都返回null。为什么会这样?
提前致谢
答案 0 :(得分:0)
添加更多信息:
恕我直言,它可能发生在newView
未被调用的行中。 :/
答案 1 :(得分:0)
这已经好几年了,但是这条线并没有按照你的想法做到:
v = l.getChildAt(position);
见ViewGroup#getChildAt()。 ListView不会覆盖此方法(尽管可能应该这样),并且只为您提供可见视图。为什么?滚动视图不存在!请记住,同样少数几个视图被回收以节省内存,但代价是这样的怪异。
试试这个:
v = l.getChildAt(position - l.getFirstVisiblePosition());
您还需要在适配器的getView()
中设置正确的背景。