我有一个 ListView 有许多不同高度的项目(动物)。使用 OnScrollListener 我试图跟踪哪个项目与屏幕上的特定位置相交。说有问题的位置是creatureMarkerBottom = 140
。当我运行代码时,下面的代码似乎返回了错误的数据:我不断收到误报和误报。这是代码。该代码应该使标记变为实心或透明,具体取决于鸡是否与其相交。然而,无论鸡是否接触板/条,褪色并没有真正服从。我的猜测是我获取 ListView 像素位置的方式是错误的。
OnScrollListener listviewScrollListener = new OnScrollListener() {
int creatureLocationPixel[] = { 0, 0 };
int creatureMarkerBottom;
int creatureTop, creatureBottom;
int[] creatureLocationPixel = { 0, 0 };
View creatureView;
boolean creatureMarkerIsFaded = false;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
try {
scrollBackgroundToFindCreature(visibleItemCount, firstVisibleItem);
} catch (Exception e) {
e.printStackTrace();
}
}
private void scrollBackgroundToFindCreature(int visibleItemCount, int index) {
creatureMarkerSlabView.getLocationOnScreen(creatureLocationPixel);
creatureMarkerBottom = creatureLocationPixel[1] + creatureMarkerSlabView.getHeight();
Animal creature;
boolean found = false;
do {
creature = mAdapter.getItem(index);
creatureView = getViewForPosition(index);
creatureView.getLocationOnScreen(creatureLocationPixel);
creatureTop = creatureLocationPixel[1];
creatureBottom = creatureTop + creatureView.getHeight();
if (creatureTop < creatureMarkerBottom && creatureMarkerBottom < creatureBottom) {
found = true;
} else {
index++;
}
} while (!found && index < visibleItemCount);
if (creatureType.CHICKEN != creature.getType()) {
if (!creatureMarkerIsFaded) {
creatureMarkerIsFaded = true;
for (int x = 0; x < creatureMarkerSlabView.getChildCount(); x++)
creatureMarkerSlabView.getChildAt(x).setAlpha(TRANSPARENCY_ALPHA);
creatureMarkerSlabView.setAlpha(TRANSPARENCY_ALPHA);
}
} else {
if (creatureMarkerIsFaded) {
creatureMarkerIsFaded = false;
for (int x = 0; x < creatureMarkerSlabView.getChildCount(); x++)
creatureMarkerSlabView.getChildAt(x).setAlpha(255);
creatureMarkerSlabView.setAlpha(255);
}
}
}
};
public View getViewForPosition(int position) {
int firstPosition = animalListview.getFirstVisiblePosition() - animalListview.getHeaderViewsCount();
int wantedChild = position - firstPosition;
// Say, first visible position is 8, you want position 10, wantedChild will now be 2
// So that means your view is child #2 in the ViewGroup:
if (wantedChild < 0 || wantedChild >= animalListview.getChildCount()) {
return null;
}
return animalListview.getChildAt(wantedChild);
}