【问题标题】:ListView backgroung color for each row android每行android的ListView背景颜色
【发布时间】:2011-05-09 03:30:34
【问题描述】:

我正在使用这段代码更改覆盖 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。为什么会这样?

提前致谢

【问题讨论】:

    标签: android listview android-layout background-color


    【解决方案1】:

    添加更多信息:

    恕我直言,这可能发生在 newView 未被调用的行中。 :/

    【讨论】:

      【解决方案2】:

      好吧,这已经有好几年了,但这条线并没有像你想象的那样:

      v = l.getChildAt(position);
      

      ViewGroup#getChildAt()。此方法不会被 ListView 覆盖(尽管它可能应该被覆盖)并且只为您提供可见的视图。为什么?滚动视图不存在!请记住,同样的少数视图会被回收以节省内存,但会以这样的怪异为代价。

      试试这个:

      v = l.getChildAt(position - l.getFirstVisiblePosition());
      

      您还需要在适配器的getView() 中设置正确的背景。

      【讨论】:

        猜你喜欢
        • 2023-03-06
        • 2012-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多