The question is published on by Tutorial Guruji team.
I have made an app for Android tv using Leanback i am using the BrowseSupportFragment and my items are rendered by class CardPresenter which implements Presenter class. I am loading images in onBindViewHolder method for the icons. But its loading too many images into memory, i checked by Logcat that the total images loaded are too many(basically around 54 rows are loaded and each row has 10-12 cards).This is causing gc pauses in application. What i want is to load only the visible images. tried using onViewAttachedToWindow method from Presenter class, But the method onBindViewHolder & onViewAttachedToWindow seems be to be called same number of times. What i want to do is to load images lazily, when the listrows are scrolled, tried searching a lot but couldn’t get proper answer, Can someone help me with that?
Answer
onBindViewHolder is the correct place to trigger the image loading. When your layout is inflated, you should see onBindViewHolder called for all visible items, sometimes with a buffer for the next item depending on the cutoff. If what you’re seeing is onBindViewHolder being called substantially more times than makes sense (e.g., you see 20 items on screen but it’s called 100 times), then you should make sure that your layouts have a set size.
For example, if you’re displaying cards and the width of a card isn’t set until after the image is loaded, your width may effectively be 0 so every card in that row is bound, triggering your image requests. ImageCardView has the setMainImageDimensions helper method to set the LayoutParams, so you can call that either in onCreateViewHolder (if the size is the same for all items) or in onBindViewHolder (if the size depends on the item).