如何确定何时片段在ViewPager变得可见片段、ViewPager

2023-09-11 10:51:27 作者:姐、活的有模有样

问题:片段 onResume() ViewPager 前的片段变成实际可见被激发

Problem: Fragment onResume() in ViewPager is fired before the fragment becomes actually visible.

例如,我有2个片段与 ViewPager FragmentPagerAdapter 。第二个片段是仅适用于授权用户,我需要让用户登录的时候,片段变为可见(使用警告对话框)。

For example, I have 2 fragments with ViewPager and FragmentPagerAdapter. The second fragment is only available for authorized users and I need to ask the user to log in when the fragment becomes visible (using an alert dialog).

但是 ViewPager 创建第二个片段时,首先是为了缓存第二个片段可见,当用户启动刷卡使其可见。

BUT the ViewPager creates the second fragment when the first is visible in order to cache the second fragment and makes it visible when the user starts swiping.

所以 onResume()事件被触发,在第二个片段后不久就变得实际可见。这就是为什么我试图找到它触发一个事件时,第二个片段成为真正可见在适当的时候显示一个对话框。

So onResume() event is fired in the second fragment long after it becomes actually visible. That's why I'm trying to find an event which fires when the second fragment becomes really visible to show a dialog at the appropriate moment.

如何才能做到这一点?

推荐答案

更新:Android的支持库(修订版11)最后固定用户可见的提示问题,现在如果您使用支持库的片段,那么你可以放心地使用getUserVisibleHint()或覆盖setUserVisibleHint()来捕获的变化所描述的高恩的回答。

UPDATE: Android Support Library (rev 11) finally fixed the user visible hint issue, now if you use support library for fragments, then you can safely use getUserVisibleHint() or override setUserVisibleHint() to capture the changes as described by gorn's answer.

过时的答案:

在大多数使用情况下,ViewPager一次只能显示一个页面,但pre-缓存的片段也投入到可见的状态(实际上是不可见的),如果你在Android的支持库$ P $使用FragmentStatePagerAdapter P-R11。

In most use cases, ViewPager only show one page at a time, but the pre-cached fragments are also put to "visible" state (actually invisible) if you are using FragmentStatePagerAdapter in Android Support Library pre-r11.

我重写:

public class MyFragment extends Fragment {
    @Override
    public void setMenuVisibility(final boolean visible) {
        super.setMenuVisibility(visible);
        if (visible) {
            // ...
        }
    }
   // ...
}

要捕捉片段的聚焦状态,我认为这是的知名度你的意思是最合适的状态,因为在ViewPager只有一个片段,实际上可以把它的菜单项与父活动的项目。

To capture the focus state of fragment, which I think is the most suitable state of the "visibility" you mean, since only one fragment in ViewPager can actually place its menu items together with parent activity's items.