4

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

petrusgomes
  • 317
  • 3
  • 12

1 Answers1

5

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

Buddy
  • 10,874
  • 5
  • 41
  • 58
  • It seens promissing! The doc is not very helpful describing the method behavior, but I will give it a try. Thanks – petrusgomes May 02 '15 at 03:37
  • I managed to use onViewAttachedToWindow to accomplish the right result, so I'm setting this as accepted answer. Thank you, @Buddy. What I did was adding impressions on the **onViewAttachedToWindow** if the fragment was visible (using [getUserVisibleHint()](http://developer.android.com/reference/android/app/Fragment.html#getUserVisibleHint())) and then sending the analytics hit **onPause** of the fragment. – petrusgomes May 05 '15 at 13:59
  • @petrusgomes can you share some code of this implementation? – Divyesh Patel Apr 13 '19 at 10:50
  • Sorry, @DivyeshPatel. I don't have access to the code anymore. But if I remember correctly, I kept the impressions in a Map, adding or removing from it as the listeners above got called. – petrusgomes Apr 22 '19 at 20:05