RecyclerView - callback when view is no longer visible

為{幸葍}努か 提交于 2019-12-03 18:38:28

问题


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)?


回答1:


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();

            }
        }
    });



回答2:


One approach you may be able to use is the following:

You can use the layoutManager.findFirstVisibleItemPosition(); and layoutManager.findLastVisibleItemPosition(); to get the first and last positions that are visible on the screen. If your item does not fall between these values, then it is off the screen.

Let me know if this is what you are looking for, or if you need/want to use another approach for some reason.




回答3:


The easiest way to do this is probably using a RecyclerListener - see the documentation available: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.RecyclerListener.html

The callback gets onViewRecycled(RecyclerView.ViewHolder holder) so you can easily tell which views are recycled.



来源:https://stackoverflow.com/questions/31683811/recyclerview-callback-when-view-is-no-longer-visible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!