检测片段内的 ViewPager 选项卡更改 [英] Detect ViewPager tab change inside Fragment

查看:37
本文介绍了检测片段内的 ViewPager 选项卡更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个片段的 ViewPager.在一个 Fragment 中,我播放音频.当我滑动到另一个片段时,我想停止音频播放.我如何检测另一个片段现在在 ViewPager 中可见?

I have a ViewPager with multiple fragments. In one Fragment I play audio. When I swipe to another fragment I want to stop the audio playback. How do I detect that the another fragment is now visible in the ViewPager?

我尝试覆盖 onStoponHiddenChanged.没有成功.必须有一些你不再活跃"的方法来覆盖.没有?

I've tried overriding onStop and onHiddenChanged. No success. There must be some "you're not active anymore" method to override. No?

推荐答案

我做了一些挖掘,结果发现 ViewPager 会同时调用:setUserVisibleHintsetMenuVisibility.我会覆盖 setUserVisibleHint 因为 文档对于 setUserVisibleHint 状态:

I did some digging and it turns out that ViewPager will call both: setUserVisibleHint and setMenuVisibility. I would override setUserVisibleHint since the documentation for setUserVisibleHint states:

向系统设置一个关于此片段的用户界面当前是否对用户可见的提示.此提示默认为 true 并且在片段实例状态保存和恢复中是持久的.应用程序可以将此设置为 false 以指示片段的 UI 已滚动到可见范围之外或以其他方式对用户不直接可见.系统可以使用它来确定片段生命周期更新或加载器排序行为等操作的优先级.

Set a hint to the system about whether this fragment's UI is currently visible to the user. This hint defaults to true and is persistent across fragment instance state save and restore. An app may set this to false to indicate that the fragment's UI is scrolled out of visibility or is otherwise not directly visible to the user. This may be used by the system to prioritize operations such as fragment lifecycle updates or loader ordering behavior.

尝试将此代码放入您的片段中:

Try putting this code in your fragment:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    // Make sure that we are currently visible
    if (this.isVisible()) {
        // If we are becoming invisible, then...
        if (!isVisibleToUser) {
            Log.d("MyFragment", "Not visible anymore.  Stopping audio.");
            // TODO stop audio playback
        }
    }
}

这篇关于检测片段内的 ViewPager 选项卡更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆