RecyclerView - callback when view is no longer visible

mroczis picture mroczis · Jul 28, 2015 · Viewed 15.9k times · Source

I have a RecyclerView with its Adapter and LayoutManager. Adapter has approximate 15 different ViewHolders. One of them contain WebView which loads external contents (99% of them are videos outside of YouTube). The problem comes when any View of Adapter gets out of the screen - video in WebView keeps playing and sound is playing. Still, that's acceptable for me.

The key problem starts when I move to another Activity. The sound of the video is still present.

Is there any way RecyclerView could notify me when any of its children views change visibility state (meaning disappears from display)?

Answer

mroczis picture mroczis · Jul 28, 2015

Gonna respond to myself. Best approach is add RecyclerView.OnChildAttachStateChangeListener to my RecyclerView and then handle events with my WebView when onChildViewDetachedFromWindow(View view) is called.

Example:

mRecyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
        @Override
        public void onChildViewAttachedToWindow(View view) {
            WebView webView = (WebView) view.findViewById(R.id.webview);
            if (webView != null) {
                webView.onResume();
            }
        }

        @Override
        public void onChildViewDetachedFromWindow(View view) {
            WebView webView = (WebView) view.findViewById(R.id.webview);

            if (webView != null) {
                webView.onPause();

            }
        }
    });