I have a HorizontalScrollView which contains a LinearLayout to hold all my view. I add about 20 RelativeLayout which contains a ImageView and TextView to the LinearLayout. I would like to only load images if the ImageView is on the screen (as I scroll to the ImageView).
I tried following this post to use getHitRect()
, on the thumbnail, however, the Rect (bounds) for the thumbnail is always 0, 0-0, 0, resulting in my method to return false. What am I doing wrong?
thumbnailLayout
is my LinearLayout inside the HorizontalScrollView
thumbnailScroll
is my HorizontalScrollView
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.e(TAG, "running");
for (int i = 0; i < thumbnailLayout.getChildCount(); i++) {
RelativeLayout view = (RelativeLayout) thumbnailLayout.getChildAt(i);
ImageView thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
if (thumbnailIsOnScreen(thumbnail)) {
Log.e(TAG, items.get(i).getTitle() + " has downloaded");
app.setImage(items.get(i).getThumbnailSmall(), thumbnail);
}
}
}
});
private boolean thumbnailIsOnScreen(ImageView thumbnail) {
Rect bounds = new Rect();
thumbnail.getHitRect(bounds);
Rect scrollBounds = new Rect(thumbnailScroll.getScrollX(), thumbnailScroll.getScrollY(),
thumbnailScroll.getScrollX() + thumbnailScroll.getWidth(), thumbnailScroll.getScrollY()
+ thumbnailScroll.getHeight());
return Rect.intersects(scrollBounds, bounds);
}
Edit I'm tred using TreeObserver and found that my method to check if the thumbails are on screen is wrong. It still grabs all the images, and constantly loops (because I'm using onPreDrawListener?)
thumbnailLayout.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
@Override
public boolean onPreDraw() {
Log.e(TAG, "running");
for (int i = 0; i < thumbnailLayout.getChildCount(); i++) {
RelativeLayout view = (RelativeLayout) thumbnailLayout.getChildAt(i);
ImageView thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
if (thumbnailIsOnScreen(thumbnail)) {
Log.e(TAG, items.get(i).getTitle() + " has downloaded");
app.setImage(items.get(i).getThumbnailSmall(), thumbnail);
}
}
return true;
}
});