larry*wei 2012-04-05 07:58 采纳率: 0%
浏览 395
已采纳

如何确定在 ViewPager 中什么时候可以看到片段

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

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

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.

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

How can this be done?

转载于:https://stackoverflow.com/questions/10024739/how-to-determine-when-fragment-becomes-visible-in-viewpager

  • 写回答

21条回答 默认 最新

  • bug^君 2012-09-21 02:56
    关注

    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.

    UPDATE 1 Here is one small problem with getUserVisibleHint(). This value is by default true.

    // Hint provided by the app that this fragment is currently visible to the user.
    boolean mUserVisibleHint = true;
    

    So there might be a problem when you try to use it before setUserVisibleHint() was invoked. As a workaround you might set value in onCreate method like this.

    public void onCreate(@Nullable Bundle savedInstanceState) {
        setUserVisibleHint(false);
    

    The outdated answer:

    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.

    I override :

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

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(20条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题