gpt4 book ai didi

android - 检测 fragment 内的 ViewPager 选项卡更改

转载 作者:IT老高 更新时间:2023-10-28 13:17:07 26 4
gpt4 key购买 nike

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

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

最佳答案

我做了一些挖掘,结果发现 ViewPager 会同时调用:setUserVisibleHintsetMenuVisibility。我会覆盖 setUserVisibleHint 因为 documentation for setUserVisibleHint状态:

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.

尝试将此代码放入您的 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
}
}
}

关于android - 检测 fragment 内的 ViewPager 选项卡更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9779397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com