Search code examples
androidgoogle-analyticsvisibleandroid-recyclerviewstaggeredgridlayout

Know when RecyclerView items are shown for the first time (Android)


I'm trying to use Google Analytics Enhanced Ecommerce to send "impressions" of my products on a RecyclerView StaggeredGrid. Every time a user scroll, I check which products are visible and send a Hit:

public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
    super.onScrollStateChanged(recyclerView, newState);

    if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
        for (int i = firstVisibleItemPosition; i <= lastVisibleItemPosition; i++) {
            Offer offer = mListViewContentFetcher.getApiObjects().get(i);

            Product product = new Product()
                .setId(offer.getCode())
                .setName(offer.getTitle())
                .setCategory(offer.getStore().getName())
                .setPosition(i);

            builder.addImpression(product, "products_list");
        }

        mTracker.setScreenName("Products List");
        mTracker.send(builder.build());
    }
}

But I also need to run this when the RecyclerView is built for the first time and the first products are visible.

How can I know that the first items are ready? I tried using ViewTreeObserver on recyclerview and onBindViewHolder without success.

Edit: This is inside a fragment that is used on a viewpager, so I need to know when the items are really visible and not only added.

Thank you


Solution

  • Can't you use your RecyclerView.Adapter's onViewAttachedToWindow and onViewDetachedFromWindow methods to track when things come in/out of view?