1

Is it possible for a view to track when it is visible and when it is no longer visible on the screen? The keyword here is track as opposed to “check”. In effect I am looking for something that behaves like onShowingOnScreen and onStopShowingOnScreen.

For some background, my view is nested quite a bit: Activity => ViewPager => Fragment => RecyclerView.Adapter => CatViewHolder => myView.

If you care: For the sake of this question, let’s assume this particular CatViewHolder is used only once while some other DogViewHolder is what gets reused multiple time.

Also, if the view cannot do this, can the ViewHolder do it? (It's effectively the same result).

update

For completeness, imagine I have to attach a slab to the window when the myView is visible and detach that slab from the window the moment myView stops being visible. ( I use slab so as not to use the word View again).

Nouvel Travay
  • 6,292
  • 13
  • 40
  • 65
  • Try this method: http://stackoverflow.com/a/31684283/1478764 – chRyNaN Apr 06 '16 at 01:28
  • Thanks for the link. Assuming I cannot change the constructor of the adapter. How do I get a pointer to the RecyclerView either from inside the adapter or from inside the ViewHolder? – Nouvel Travay Apr 06 '16 at 01:41

1 Answers1

1

First, the view must be attached to the current view hierarchy. So you'll need to register a OnAttachStateChangeListener with this method on the view to see if it even could be visible.

You can then call getWindowVisibleDisplayFrame() to find out Android has allocated any display space to it.

Mike M.
  • 38,532
  • 8
  • 99
  • 95
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • This answer is quite promising so thank you very dearly (+1). Really thank you. But a few problems arise. There is a ViewPager in the hierarchy. Hence, the attached will be called about three pages away and the detached will be called about three pages away: whereas I need to perform the action at the precise moment the user is on the page displaying **myView** or away from the page displaying **myView**. The dead-band presents a bit of a problem. – Nouvel Travay Apr 06 '16 at 02:01
  • You can choose the moment that getWindowVisibleDisplayFrame is called, from the main thread. It just won't give you the value you want if you do it while the view is not attached. – Doug Stevenson Apr 06 '16 at 02:43